-
Error in code
Code:
Can anyone find logical error in this code,explain it and how to fix???
int myNumber;
int sum = 0;
Console.Write("Enter value : " );
myNumber = int.Parse(Console.ReadLine());
while (myNumber != -999
{
Console.Write(Enter value :");
myNumber = int.Parse(Console.ReadLine());
sum = sum + myNumber;
}
Console.WriteLine("Sum is {0}", sum);
-
I don't know about logical, but you've got a syntactical problem:
Code:
while (myNumber != -999)
-
what is the problem with this??
-
You don't add the first number input to the sum since you ask for a new number before the 'summing'
-
- Also you aren't validating user input. If the user inputs "joe", your code will crash with an unhandled exception (System.FormatException). Either wrap the Parse statement inside a try-catch clause, or use Int32.TryParse().
- Also, you aren't testing for -999 inside the while statement, which means at least one instance in which the user inputs -999 will be accepted.
Code:
while (myNumber != -999) {
Console.Write("Enter value : " );
if (int.TryParse(Console.ReadLine(), myNumber) && myNumber != -999) // C# supports short-circuit evaluation, no harm done
sum = sum + myNumber;
}
-
This sounds like homework or a programming test.
-
Just cycling through past exams papers and came across it...
not homework