Okay at the moment I my self am new to programming and learning it slowly. At the moment I am taking programming classes to help better understand programming. I have ran in to a problem that has stumped me.
Now while I can do the assignment in a different way and manner as compared to what I provided. My question is, why is this happening? I get no errors, what so ever, the only thing that happens is after the input the Console Fezzes. I want to know what I did wrong.
static void Main(string[] args)
{
double[] Population = new double[6];
string[] Years = { "2", "3", "4", "5", "6", "7" };
double GrowthPercentage = 0.0;
double MathPercentage = 0.0000;
double ActualGrowth = 0.0;
int WhileCounter = 0;
//Ask user for Population of Roarkville
Console.WriteLine("Enter the Population of RoarkVille: ");
//Read Population and store
Population[0] = Convert.ToDouble(Console.ReadLine());
//Ask user for Growth percentage
Console.WriteLine("Enter the Growth percentage ");
//Read Growth Percentage
GrowthPercentage = Convert.ToDouble(Console.ReadLine());
//Calculation of Growth Percentage: Growth Percentage/100 = Math Percentage
MathPercentage = GrowthPercentage / 100;
//ActualGrowth = Population * Math Percentage
//Population2 = ActualGrowth + Population
while (WhileCounter < 5)
{
ActualGrowth = Population[WhileCounter] + MathPercentage;
WhileCounter++;
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
//Display 2012 Population
//Display 2013 Population
//Display 2014 Population
//Display 2015 Population
//Display 2016 Population
//Display 2017 Population
Console.ReadLine();
}
so what happen is that when you input on the growth percentage using this code:
while (Counter < 5)
{
ActualGrowth = Population[Counter] + MathPercentage;
Counter++;
Population[Counter] = ActualGrowth + Population[Counter--];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
the numbers that will you input will be infinite on the growth percentage:
this one can help you also
while (Counter < 5)
{
ActualGrowth = Population[Counter] + MathPercentage;
Counter++;
Population[Counter] = ActualGrowth + Population[Counter-1];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
The ++ operator changes the actual value of the variable, so WhileCounter++ increases the variable by 1
The -- operator does the same, which is not what you want to do in the line
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
Instead, use WhileCounter - 1 , like so
Population[WhileCounter] = ActualGrowth + Population[WhileCounter - 1];
WhileCounter++;
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
The value of WhileCounter never changes as far as the loop is concerned. In the loop body you increment WhileCounter and proceed to immediately decrement it, so the condition WhileCounter < 5 is always true.
You may as well have written
int WhileCounter = 0;
while(WhileCounter < 5)
{
WhileCounter += 1; // WhileCounter == 1
WhileCounter -= 1; // WhileCounter == 0
}
// aint never gunna happen
You should read up on the following operators and understand what they actually do:
--
++
Related
I am trying to do a calculation which involves a do while loop in c#
I want to execute the loop and minus the quantum from the remainingTime array and assign the new value to timeelapsed.
My loop should execute while timeelapsed is > 0 and stop once it hits 0
However, the loop does not carry out the - quantum part of the code, i don't understand why.
static void Main(string[] args)
{
int quantum, noOfProcesses, processNumber = 0; // noOfprocesses variable is to determine array sizes, processNumber tells user what process number they input
int timeelapsed, count = 0;
Console.WriteLine("Please enter the number of processes:");
noOfProcesses = Convert.ToInt32(Console.ReadLine()); // allows numerical input
int[] bursttime = new int[noOfProcesses];
int[] arrivalTime = new int[noOfProcesses];
int[] remainingTime = new int[noOfProcesses];
for (int i = 0; i < noOfProcesses; i++)
{
Console.WriteLine("Enter Burst time for process #" + processNumber);
bursttime[i] = Convert.ToInt32(Console.ReadLine());
processNumber++;
}
processNumber = 1; // resets the process number for user interface
for (int i = 0; i < noOfProcesses; i++)
{
Console.WriteLine("Enter arrival time for process #" + processNumber);
arrivalTime[i] = Convert.ToInt32(Console.ReadLine());
processNumber++;
}
Console.WriteLine("Enter the time quantum:");
quantum = Convert.ToInt32(Console.ReadLine()); // allows numerical input
// calculations
processNumber = 0;
if (count <= noOfProcesses)
{
// remainingTime[0] = bursttime[0] + arrivalTime[0]; // burst + arrival = remaining time
for (int i = 0; i < noOfProcesses; i++)
{
do
{
remainingTime[i] = bursttime[i] + arrivalTime[i]; // burst + arrival = remaining time
timeelapsed = remainingTime[i] - quantum; // - the quantum gives whats remaining
timeelapsed = timeelapsed - quantum;
}
while (timeelapsed > 0);
Console.WriteLine("#" + processNumber + " Time taken: " + timeelapsed + "ms");
processNumber++;
count++;
//timeelapsed = bursttime[i] + arrivalTime[i];
}
}
// Console.WriteLine(arrivalTime[j]);
Console.ReadLine();
}
Please note that the noOfProcesses and processNumber variables are defined in the program i don't believe these are causing the issue.
All you are doing in this loop is recalculating the same values over and over again:
do {
remainingTime[i] = bursttime[i] + arrivalTime[i]; // burst + arrival = remaining time
timeelapsed = remainingTime[i] - quantum; // - the quantum gives whats remaining
timeelapsed = timeelapsed - quantum;
} while (timeelapsed > 0);
For example, you might see this if you use real numbers:
do {
remainingTime = 100 + 100;
timeelapsed = 200 - 10
timeelapsed = 190 - 10;
} while (timeelapsed > 0);
The loop never ends. I'm not sure exactly what your goal is, but you probably need to keep a running total, like:
remainingTime[i] += bursttime[i] + arrivalTime[i];
Or
remainingTime[i] -= bursttime[i] + arrivalTime[i];
This is really debugging and tough to decide without having the code in front of me. I'm assuming that the 'quantum' code is the section in the do part of the loop. In which case, the only reason why it isn't running is one of the three:
noOfProcesses is less than 1
timeelapsed is <= 0
It is getting to the first iteration of the loop but an exception is being thrown.
Since you're using c#, and hopefully VS, you should use the debugger and step through your program.
I don't know why but when I'm trying to compile the next code I'm getting error CS1525 and every ) at the end of every while command is being marked as an error:
static void PrintArray(string[] arr)
{
int i, sum = 0, subb = 0, pow, x;
char opper;
Console.WriteLine("how many numbers does your calculation have?");
i = Convert.ToInt16(Console.ReadLine());
arr = new string[i];
for (i = 0; i < arr.Length; i++)
{
Console.WriteLine("enter num {0}" + i);
arr[i] = Console.ReadLine();
Console.WriteLine("arr[{0}] = {1}" + i, arr[i]);
}
Console.WriteLine("what do you want to do?");
opper = Convert.ToChar(Console.ReadLine());
while (opper = +)
{
for (i = 0; i < arr.Length; i++)
{
sum = sum + Convert.ToInt16(arr[i]);
}
Console.WriteLine("your sum is " + sum);
}
while (opper = -)
{
for (i = 0; i < arr.Length; i++)
{
subb = subb + Convert.ToInt16(arr[i]);
}
Console.WriteLine("your subb is" + subb);
}
while (opper = *)
{
pow = Convert.ToInt16(arr[0]);
for (i = 1; i < arr.Length; i++)
{
pow = pow * Convert.ToInt16(arr[i]);
}
Console.WriteLine("the resolt is " + pow);
}
while (opper = &)
{
x = Convert.ToInt16(arr[i]);
for (i = 0; i < arr.Length; i++)
{
x = x / Convert.ToInt16(arr[i]);
}
Console.WriteLine("your resolt is " + x);
}
Console.ReadKey();
}
I will be glad if someone can finally explain that to me...
Given the lines (for example)
opper = Convert.ToChar(Console.ReadLine());
while (opper = +)
It looks like you're trying to compare the character input to an operator. You'll want to change the assignment operator to a comparison operator, and compare the character to another character, like so:
opper = Convert.ToChar(Console.ReadLine());
while (opper == '+')
user1673882 is correct here about the cause of the compile error. However, there are several other significant bugs you should be aware of as well.
As for the original compile issue, you have two issues with the following line (and all similar lines);
while (opper = +)
First, = (single "equals" sign) is assignment, not comparison. You want to use == here instead.
Secondly, + is not a character in this case, it's an operation. (In fact, the compiler can't infer exactly which operator it might be).
Even if you get this to compile, though, it won't work because all of your loops are infinite loops. Consider this example:
char myChar = 'a';
// Infinite loop
while (myChar == 'a')
{
Console.WriteLine("Test");
}
How could this possibly get out of the loop, given that myChar will always be a?
A few other miscellaneous bugs follow:
subb = subb + Convert.ToInt16(arr[i]);
This could be shortened with
subb += Convert.ToInt16(arr[i]);
or possibly even
subb += (short)arr[i];
Also, I'm assuming this shouldn't be "+" since that's exactly the same operation you're doing if the operation is "+" (i.e. the outcome of "+" and "-" should be exactly the same).
x = x / Convert.ToInt16(arr[i]);
First, same cleanup as above:
x /= (short)arr[i];
Secondly, you never test for division by 0 here, so this might throw an exception.
Third, I'm not sure what type x is, but "short" is definitely not closed over division - i.e.:
short a = ...
short b...
// May not be another short
Console.WriteLine(a / b);
Actually, this applies to multiplication, subtraction, and addition to some extent too in this case since shorts have a finite size. Consider the following code:
short overflow = short.MaxValue;
// -32768
overflow++;
// +32767
overflow--;
// -32768 again
overflow++;
// -32767
overflow++;
checked
{
overflow = short.MaxValue;
// Now this results in an OverflowException
overflow++;
}
One more example:
short testArithmetic = 1;
// This gives us the result that 1 / 2 = 0.
testArithmetic /= 2;
// Set this back to 1 for the next operation
testArithmetic = 1;
// This is 0.0 too!
double testArithmeticFloat = testArithmetic / 2;
// This gives us the result we'd expect
testArithmeticFloat = 1.0 / 2.0;
// This'll compile just fine, but you get a DivideByZeroException when you try to execute it
testArithmetic /= 0;
I make a loop like this :
int total;
total = ((toVal - fromVal) + 1) * 2;
RadProgressContext progress = RadProgressContext.Current;
progress.Speed = "N/A";
finYear = fromVal;
for (int i = 0; i < total; i++)
{
decimal ratio = (i * 100 / total);
progress.PrimaryTotal = total;
progress.PrimaryValue = total;
progress.PrimaryPercent = 100;
progress.SecondaryTotal = 100; // total;
progress.SecondaryValue = ratio;//i ;
progress.SecondaryPercent = ratio; //i;
progress.CurrentOperationText = "Step " + i.ToString();
if (!Response.IsClientConnected)
{
//Cancel button was clicked or the browser was closed, so stop processing
break;
}
progress.TimeEstimated = (total - i) * 100;
//Stall the current thread for 0.1 seconds
System.Threading.Thread.Sleep(100);
}
Now i want a specific method to run according to toVal & fromVal
in the previous loop but not with the same number of cycles
i want to to run it in a loop like this :
for (fromVal; fromVal < toVal ; fromVal++)
{
PrepareNewEmployees(calcYear, fromVal);
}
for example :
fromVal = 2014
toVal = 2015
so i want to run twice not 4 times! like this :
PrepareNewEmployees(calcYear, 2014);
PrepareNewEmployees(calcYear, 2015);
but in the previous loop for (int i = 0; i < total; i++)
You're missing the point of progress bar updating. You're not supposed to run 4 iterations and do some work every 2 iterations, but the oposite. Do a loop like:
for (int i = fromVal; i < toVal; i++)
{
PrepareNewEmployees(...);
decimal ratio = ((double)toVal-i)/(toVal-fromVal) *100;
//Some other things, that need to be done twice in an iteration
}
Because you are using Thread's already, consider to implement following:
public void ResetProgress()
{
SetProgress(0);
}
public SetProgress(int percents)
{
// set progress bar to a given percents/ratio
// you will have to use Invoke and blablabla
}
Then any your job will looks like this
ResetProgress();
// note: you need to remember from which value you start to be able to calculate progress
for (int i = startVal; i < toVal ; i++)
{
PrepareNewEmployees(calcYear, i);
SetProgress(100 * (i - startVal) / (toVal - startVal)); // in percents [0-100]
}
// optional, required if you exit loop or use suggestion below
SetProgress(100);
You can also optimise it, to do not update progress after each step, but after certain numbers of steps. To example, instead of calling SetProgress you do
if(i % 10 == 0)
SetProgress();
This will calls SetProgress ten times less often. Of course, there are some assumptions, like: i starts from 0 and if you want to have 100% bar at the end, then i should be dividable by 10. Just an idea to start.
Here's the problem:
Write a program named TipsList that accepts seven double values
representing tips earned by a waiter each day during the week. Display
each of the values along with a message that indicates how far it is
from the average.
This is what I have figured out so far.
static void Main(string[] args)
{
double[] tips;
tips = new double[7];
double one = tips[0];
double two = tips[1];
double three = tips[2];
double four = tips[3];
double five = tips[4];
double six = tips[5];
double seven = tips[6];
double average = (one + two + three + four + five + six + seven) / 7;
//Now I am trying to take the tip 1,2,3,4,5,6, and 7 that the user has entered
//And display the diffrence of tip 1,2,3,4,5,6, and 7 from the average
//So one-average = tip 1 console.Write tip1 ??????
for (int i = 0; i <= 6; i++)
{
Console.Write("Please enter the amount of tips earned by waiter #" + i + ".");
tips[i] = Console.Read();
Console.Write("tips 1????????????HELP");
}
}
}
I have an understanding of how I would try and do it and think I should do
one-average = tip 1 console.Write tip1 ?????
but C# doesn't like it. I just don't get it still does C# only let me do it in 1 determined way.
I just realised this is for a class so I'd stay away from Linq, it would be too obvious for any teacher.
Simply just write out the value of each taken away from the average
foreach(double tip in tips)
{
Console.WriteLine(Average - tip);
}
Edit Just realised the problem is getting the input.
Your better off to use TryParse as this will handle invalid input
while(!double.TryParse(Console.ReadLine(), out tips[i]))
{
Console.WriteLine("Thats not a valid number");
}
Use somthing like this:
double[] tips = new double[7];
for (int i = 0; i < tips.Length; i++)
{
Console.Write("Please enter the amount of tips earned by waiter #" + i + ": ");
tips[i] = double.Parse(Console.ReadLine());
}
double average = tips.Average();
//without linq
/*
double sum = 0;
for (int i = 0; i < tips.Length; i++)
{
sum = sum + tips[i];
}
double average = sum / tips.Length;
*/
for (int i = 0; i < tips.Length; i++)
{
Console.WriteLine("Tip #" + i + " is: " + tips[i] + " - The difference between the average is: " + Math.Abs(tips[i] - average));
}
Console.ReadLine()
I was doing this program myself, and i realized that it is actually asking for a 2D array hence the 7 inputs for the 7 days of the week. you can accomplish that by usingdouble[,] tips = new double[7, 7];Then you would use 2 loops to access each index element
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
{
tips[i, j] = int.Parse(Console.ReadLine());
}
}`
Then you would first get an average(i.e add the sum of all indexes per day(7) or for the week(49) depending on how accurate you would want your data to be, then divide)
I am trying to develop a console application in C# which uses a WAV-file for input. The application should do a couple of things all in order, as shown below. First of all, the complete code:
class Program
{
static List<double> points = new List<double>();
static double maxValue = 0;
static double minValue = 1;
static int num = 0;
static int num2 = 0;
static List<double> values = new List<double>();
private static object akima;
static void Main(string[] args)
{
string[] fileLines = File.ReadAllLines(args[0]);
int count = 0;
foreach (string fileLine in fileLines)
{
if (!fileLine.Contains(";"))
{
string processLine = fileLine.Trim();
processLine = Regex.Replace(processLine, #"\s+", " ");
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
processLine = processLine.Replace(".", ",");
}
string[] dataParts = processLine.Split(Char.Parse(" "));
points.Add(double.Parse(dataParts[0]));
double value = Math.Pow(double.Parse(dataParts[1]), 2);
if (value > maxValue)
{
maxValue = value;
num = count;
}
values.Add(value);
}
count++;
}
for (int i = num; i < values.Count; i++)
{
if (values[i] < minValue)
{
minValue = values[i];
num2 = i;
}
}
Console.WriteLine(num + " " + num2);
int between = num2 - num;
points = points.GetRange(num, between);
values = values.GetRange(num, between);
List<double> defVal = new List<double>();
List<double> defValPoints = new List<double>();
alglib.spline1dinterpolant c;
alglib.spline1dbuildakima(points.ToArray(), values.ToArray(), out c);
double baseInt = alglib.spline1dintegrate(c, points[points.Count - 1]);
List<double> defETC = new List<double>();
for (int i = 0; i < points.Count; i += 10)
{
double toVal = points[i];
defETC.Add(10 * Math.Log10(values[i]));
defVal.Add(10 * Math.Log10((baseInt - alglib.spline1dintegrate(c, toVal)) / baseInt));
defValPoints.Add(points[i]);
}
WriteDoubleArrayToFile(defValPoints.ToArray(), defVal.ToArray(), "test.dat");
WriteDoubleArrayToFile(defValPoints.ToArray(), defETC.ToArray(), "etc.dat");
int end = 0;
for (int i = 0; i < points.Count; i++)
{
if (defVal[i] < -10)
{
end = i;
break;
}
}
//Console.WriteLine(num + " " + end);
int beginEDT = num;
int endEDT = num + end;
double timeBetween = (defValPoints[endEDT] - defValPoints[beginEDT]) * 6;
Console.WriteLine(timeBetween);
for (int i = 0; i < points.Count; i++)
{
}
Console.ReadLine();
}
static void WriteDoubleArrayToFile(double[] points, double[] values, string filename)
{
string[] defStr = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
defStr[i] = String.Format("{0,10}{1,25}", points[i], values[i]);
}
File.WriteAllLines(filename, defStr);
}
}
Extract the decimal/float/double value from the WAV-file
Create an array from extracted data
Create an Energy Time Curve that displays the decay of the noise/sound in a decibel-like way
Create an Decay Curve from the ETC created in step 3
Calculate things as Early Decay Time (EDT), T15/T20 and RT60 from this Decay Curve.
Display these Reverb Times in stdout.
At the moment I am sort of like half way through the process. I´ll explain what I did:
I used Sox to convert the audio file into a .dat file with numbers
I create an array using C# by simply splitting each line in the file above and putting the times in a TimesArray and the values at those points in a ValuesArray.
I am displaying a graph via GNUPlot, using the data processed with this function: 10 * Math.Log10(values[i]); (where i is an iterative integer in a for-loop iterating over all the items in the ValuesArray)
This is where I'm starting to get stuck. I mean, in this step I am using an Akima Spline function from Alglib to be able to integrate a line. I am doing that with a Schroeder integration (reversed), via this mathematical calculation: 10 * Math.Log10((baseInt - alglib.spline1dintegrate(c, toVal)) / baseInt); (where baseInt is a value calculated as a base integral for the complete curve, so I have a calculated bottom part of the reversed Schroeder integration. The c is a spline1dinterpolant made available when using the function alglib.spline1dbuildakima, which takes the timeArray as x values, valueArray as the y values, and c as an outwards spline1dinterpolant. toval is an x-value from the points array. The specific value is selected using a for-loop.) From these newly saved values I want to create an interpolated line and calculate the RT60 from that line, but I do not know how to do that.
Tried, did not really work out.
Same as above, I have no real values to show.
I'm quite stuck now, as I'm not sure if this is the right way to do it. If anyone can tell me how I can calculate the reverberation times in a fast and responsive way in C#, I'd be pleased to hear. The way of doing it might be completely different from what I have now, that's OK, just let me know!
Maybe you need to approach this differently:
start with the underlying maths. find out the mathematical formulas for these functions.
Use a simple mathematical function and calculate by hand (in excel or matlab) what the values should be (of all these things ETC, DC, EDC, T15, T20, RT60)
(A function such as a sine wave of just the minimum number of points you need )
then write a separate procedure to evaluate each of these in C# and verify your results for consistency with excel/matlab.
in C#, maybe store your data in a class that you pass around to each of the methods for its calculation.
your main function should end up something like this:
main(){
data = new Data();
//1, 2:
extract_data(data, filename);
//3:
energy_time_curve(data)
//...4, 5
//6:
display_results(data);
}