I need to read the number inputs from the user until they type in 0, print the sum of all entered number.
I am hoping to get this response:
Enter n: 50
Enter n: 25
Enter n: 10
Enter n: 0
total=85
So far my code is (sorry for my variables):
char ya;
float tem, ye, sum, roun=0.0;
printf("Enter n: ");
scanf("%f" ,&ye);
while (ye > 0 || tem > 0)
{
printf("Enter n: ");
scanf("%f", &tem);
roun = roun tem;
}
sum = sum ye;
printf("Total= %f\n", sum);
CodePudding user response:
There are a few issues with the code you have shared. First of all for the code you have provided, you need to ensure temp is also initialised to 0. i.e temp=0
Then you already have some value in ye means the loop will not terminate. You once you are inside while loop, you need to reset the value of ye to 0. But before that you need to include the value of ye in the sum. So you will have to sum = sum ye before the while loop.
Also in your code, you need to add round to sum and not ye. So if I was to correct your code, it will look like below
tem=0;
printf("Enter n: ");
scanf("%f" ,&ye);
roun=ye;
while (ye > 0 || tem > 0)
{
printf("Enter n: ");
scanf("%f", &tem);
roun = roun tem;
ye=0;
}
sum = sum roun;
printf("Total= %f\n", sum);
but a better approach is to use do-while loops rather and have a code like below
do
{
printf("Enter n: ");
scanf("%f", &tem);
sum = sum tem;
} while(tem>0);
printf("Total= %f\n", sum);
CodePudding user response:
roun = roun tem;
You add the values to roun
, not sum
. So noun
should be the final value.
Then,
sum = sum ye;
does not make sense. Because sum
is uninitialized and it's value in indeterminate.
Aside: You can write sum = ye;
instead of sum = sum ye;
.