所以我正在写一个基本的程序,要求用户输入一个数字,循环将继续,直到他们输入一个特定的数字。(25)。然后,程序会将他们输入的所有数字相加。问题是当我输入退出编号时,循环不会退出,并且我不确定原因。
double userNum = 0;
double sum = 0;
do {
printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n");
scanf("%f", &userNum);
sum = sum + userNum;
} while (userNum != 25);
printf("The sum of all the numbers you entered:%f\n", sum);此外,我不确定总和是否会正确计算,因为我从来没有能够退出循环。
发布于 2016-10-03 08:51:36
你想使用一个前哨控制的循环(25是你的前哨)。以下是我要写的内容:
#include <stdio.h>
int main()
{
double userNum = 0;
double sum = 0;
while ( userNum != 25 ) { //sentinel controlled loop
puts("Please enter a number you would like to add [Enter 25 to exit at any time]:"); // puts automatically inputs a newline character
scanf("%lf", &userNum); // read user input as a double and assign it to userNum
sum = sum + userNum; // keep running tally of the sum of the numbers
if ( userNum == 25 ) { // Subtract the "25" that the user entered to exit the program
sum = sum - 25;
} // exit the if
} // exit while loop
printf("The sum of all the numbers you entered:%lf\n", sum);
} // exit main或者,您可以坚持使用do...while:
// Using the do...while repetition statement
#include <stdio.h>
// function main begins program execution
int main( void )
{
double userNum = 0; // initialize user input
double sum = 0; //initialize sum as a DOUBLE
do {
puts("Please enter a number you would like to add [Enter 25 to exit at any time]:"); // puts automatically inputs a newline character
scanf("%lf", &userNum); // read user input as a double and assign it to userNum
sum = sum + userNum; // keep running tally of the sum of the numbers
if ( userNum == 25 ) { // Subtract the "25" that the user entered to exit the program
sum = sum - 25;
} // end if statement
} while ( userNum != 25 ); // end do...while
printf("The sum of all the numbers you entered:%lf\n", sum);
} // end function mainhttps://stackoverflow.com/questions/39822819
复制相似问题