I'm trying to add the complete total of all TotalPrice for the 5 inputs, when I add this:
for(x= 0; x < InputOrder.Length; ++x){
Console.WriteLine("Total is ${0}", InputOrder[x].TotalPrice++);
I get an error message when compiling:
error CS0200: Property or indexer 'System.Order.TotalPrice
cannot be assigned to -- it is read only
When I write it like this it compiles and the output is correct, it just seems like there is a much better way to do it
Console.WriteLine("Total is ${0}",
(InputOrder[0].TotalPrice +
InputOrder[1].TotalPrice +
InputOrder[2].TotalPrice +
InputOrder[3].TotalPrice +
InputOrder[4].TotalPrice));
Any help would be appreciated
Console.WriteLine("Total is ${0}", InputOrder.Sum(x=>x.TotalPrice));
It's not array, it's Your InputOrder.TotalPrice which is protected
Old school:
int total = 0;
for(x= 0; x < InputOrder.Length; ++x){
total += InputOrder[x].TotalPrice;
Console.WriteLine("Total is ${0}", total);
LINQ:
Console.WriteLine("Total is ${0}", InputOrder.Sum(item => item.TotalPrice));
Related
Hello good people.
So I am struggling a little with the while/for/do while loops as I am having trouble understanding their structure.
And that causes me to have some issues with my homework assignment , what I need to do is a write a code for the following:
I need a program that allows a user to input only positive and whole numbers , the program also calculates their sum and shows the result for each input in the console ( for example the user inputs 1 and than 2 and than 3 and than 4 the program will show the result as 10).
The program will end if the user has input 0 or a negative number.
I can only use for / while / do while.
My experience is really with only the basic stuff like int , double , loop , string , etc'
I can't really wrap my head around it very much and I would love to get some ideas and assistance.
I've tried but got stuck at the beginning has I have no idea how to start with it
edit:
I've really just dabbled with the idea because I have no idea how to start , I've made this, it was no good
int number, i=1 , min;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
while (i <= number)
{
Console.WriteLine("This is the smallest number: " + number);
i++;
}
edit: I did this, but I wonder if there's a better way
int number, sum = 0;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
start:
number = int.Parse(Console.ReadLine());
while (number > 0)
{
Console.WriteLine("This is your number : " + number);
sum += number;
Console.WriteLine("The sum is: " + sum);
goto start;
}
while (number <= 0)
{
Console.WriteLine("Please enter a number bigger than 0");
break;
}
Loops are for code that repeats. In your task, input and addition repeat, so put them in loop. while and for loops check the condition before executing loop body, and do checks after.
Your algorithm is like that:
Read input.
Check if it's positive, if it's not, exit.
Add it to sum.
Repeat.
So you should check the condition in the midst of loop. You can use break to exit loop early. Since you neither check condition in beginning nor end, just write an infinite loop.
int n, sum = 0;
while (true) {
n = int.Parse (Console.ReadLine ());
if (n <= 0) break;
sum += n;
}
Updated. Yes you can shorten your code.
int number, sum = 0;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
start:
number = int.Parse(Console.ReadLine());
You put a repeating statement outside of loop. It forced you to use a label. Labels can easily make your logic very difficult to read.
while (number > 0)
{
Console.WriteLine("This is your number : " + number);
sum += number;
Console.WriteLine("The sum is: " + sum);
goto start;
You exit the loop indefitinely, so that's no difference between while and if here.
}
while (number <= 0)
{
Console.WriteLine("Please enter a number bigger than 0");
break;
And the same again.
}
Remember to use loop when something repeats and don't use when nothing does.
Console.WriteLine ("Please enter only positive WHOLE numbers to calculate");
int n, sum = 0;
while (true) {
n = int.Parse (Console.ReadLine ());
Console.WriteLine ("This is your number : " + number);
if (n <= 0) {
Console.WriteLine("Please enter a number bigger than 0");
// actually he won't get a chance to enter it. Why to ask him then?
break;
}
sum += n;
Console.WriteLine("The sum is: " + sum);
}
1 way of doing it:
int number, i=0 , min=1; // min is the minimum value, i is the sum, number is the input you give
while (i <= min)// checks if its lesser than zero
{
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
i += number;
Console.WriteLine("This is the sum: " + i);
}
Other way of doing it:
int number, i=0 , min=1; // min is the minimum value, i is the sum, number is the input you give
while (true)
{
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
if(i<=min)
break;
i += number;
Console.WriteLine("This is the sum: " + i);
}
I think the best thing to do is read the documentation:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do
I need some clarification. I'm doing a lab project that wants me to gather 5 numbers, then when a button is clicked it adds them, divides them into dozens, and also tells the remainder. here's a portion of my code, I'm wanting to know if there's something I'm missing in the line with label2?
int sum = num1 + num2 + num3 + num4 + num5;
int dozen = sum / 12;
int remainder = sum % 12;
label2.Text = "The total is {0}. That's {1} dozen with {2} remainders",sum , dozen, remainder;
}
}
}
any help would be appreciated.
Yes, you're missing a call to string.format or nowadays you can do:
label2.Text = $"The total is {sum}. That's {dozen} dozen with {remainder} remainders";
Change to this:
label2.Text = String.Format("The total is {0}. That's {1} dozen with {2} remainders",sum , dozen, remainder);
String.Format take arguments.
I have a program, in which an event happens randomly. I'm trying to write some code to calculate and store the average time it takes for these events to happen. Here is the code I use to calculate the mean:
int EventCount = 0;
var s = Stopwatch.StartNew();
while(true)
{
if (EventTriggered)
{
Console.WriteLine("Event detected");
EventCount++;
s.Stop();
AverageMS+= s.ElapsedMilliseconds;
AverageMS /= EventCount;
Console.WriteLine("Current average ms: " + AverageMS);
s.Restart();
}
}
The supposed average milliseconds it displays look to be closer to the individual times instead of the average.
Here is a sample of 100 events:
http://pastebin.com/cmwQPqfR
You are dividing the average by the event count, meaning you are dividing over and over again. You need to accumulate the total, then recompute the average each time.
More like this:
long TotalMS = 0;
int EventCount = 0;
var s = Stopwatch.StartNew();
while(true)
{
if (EventTriggered)
{
s.Stop();
Console.WriteLine("Event detected");
EventCount++;
TotalMS+= s.ElapsedMilliseconds;
AverageMS = TotalMS / EventCount;
Console.WriteLine("Current average ms: " + AverageMS);
s.Restart();
}
}
Note that you should stop your timer before the WriteLine, otherwise you are timing the console operation as well.
Your calculations are wrong. You should keep the count and total elapsed time separately an do the division when you need to. Look at What you are doing if your elapsed times are 1, 3, 5. Clearly the averages should go 1, 2 and 3. What you will get is (EventCount =1; AverageMS = 1). Then you'll get EventCount = 2, AverageMS has 3 added then is divided by 2 so Average is (1+3)/2 = 2. Then EVentCount goes to 3 and Average MS = (2+5)/3 = 2.333 (going wrong now, should be 3). If the next is 3 then the average would be (2.333+3)/4 = 1.3333!.
Just keep the count and running total separate to fix it.
How to find a loop that will successfully add 5 numbers. Here is the homework question.
Add a loop that will take a number input by the user and add it to a running total (the ReadLine() method will get a string from the user).
You’ll notice in the above code there are two variables declared.
One is total of the double data type which will have the total of the 5 entered numbers.
The other is a temp string variable to take the user input, convert to double, and then add the converted value to the total.
Using what you have learned in case 2 about taking input and converting to an int32, take the input and convert ToDouble() instead of int32.
total = total + Convert.ToDouble(temp);
case "3":
double total = 0;
string temp = "0";
Console.WriteLine("Enter 5 numbers here for addition \n");
for (total = 0; total <= 6; total++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
break;
When I tried entering this in, the debugging program exited out and gave me a set number.
It keeps saying that string will not convert to integer when I tried entering string as an expressions instead.
Here is the result I am trying to get.
1
2
3
4
5
Total:15 This is the answer I am trying to get.
You set temp to be an empty string and then it never becomes a number, hence you can't cast it to a double....
Convert.ToDouble(input) won't do anything either as you need to store the value, i.e.
double result = Convert.ToDouble (input)
The loop is wrong because you only ever take one input - you need to put your Console.ReadLine in your loop and then append what the user inputs to your total.
you probably need to do:
int index=Convert.ToDouble(input);
and use in the for loop something like
for(int i=0;i<index;i++)
since as it stands you retrieve an input but don't use it, in for loop in fact you're trying to set it to zero -> for(input=0;....)
which can't be done since input is a string and not a number
in case 3 you're using total as an index and as the total variable in the calculation you can't do that
you need another variable to use as a index:
for (int i = 0; i<= 6; i++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
Console.Write("Enter how many numbers you want to enter and sum up: ");
double n = double.Parse(Console.ReadLine());
double r;
double sum = 0;
for (int i = 0; i < n; i++)
{
Console.Write("{0} Enter number ", i);
r = double.Parse(Console.ReadLine());
sum += r;
Console.WriteLine(sum);
}
So I'm intentionally overcomplicating a homework assignment I was given because I was bored and wanted to learn more about c#. The original assignment is as follows:
"Compute the average of five exam scores ranging between 50 and 90. Declare and perform a compile-time initialization with the five values. Use a constant to define the number of scores. Display all scores and the average value formatted with no digits to the right of the decimal."
So I decided rather than just putting the 5 scores in, I'd allow the user to input them into an array and then calculate it from that.
Console.WriteLine("Enter 5 test scores between 50 and 90:");
int i = 0;
double total = 0;
double[] Scores;
Scores = new double[5];
while (i < 5)
{
Console.WriteLine("Input Score " + (i + 1) + ":");
String input = Console.ReadLine();
Scores[i] = double.Parse(input);
total += Scores[i];
i++;
}
Console.WriteLine("The average of the scores is: " + (total/5));
The issue is that the Scores[i] = double.Parse(input); is throwing an error saying that the input is in the wrong format. So the program won't even run to let me put IN an input, but it says the input format is incorrect.
Any suggestions? I'm probably missing something obvious.
EDIT: Ok, so what ended up working was changing the code to
Console.WriteLine("Input Score " + (i + 1) + ":");
Scores[i] = double.Parse(Console.ReadLine());
total += Scores[i];
i++;
Not sure what it actually changed but it seems to work pretty flawlessly!