所以我正在写一个基本的程序,要求用户输入一个数字,循环将继续,直到他们输入一个特定的数字。(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 07:55:18
考虑使用fgets作为输入,并使用sscanf解析值。这样,您可以输入done或exit来终止循环,而不是输入25。扫描双精度图的格式是%lf。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( void)
{
char input[99] = "";
double userNum = 0;
double sum = 0;
while ( 1) {
printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n");
if ( ( fgets ( input, sizeof ( input) , stdin))) {
if ( strcmp ( input, "25\n") == 0) {//could use exit, done ... instead of 25
break;
}
if ( ( sscanf(input, "%lf", &userNum)) == 1) {//sscanf successful
sum = sum + userNum;
}
}
else {
break;//fgets failed
}
}
printf("The sum of all the numbers you entered:%f\n", sum);
return 0;
}发布于 2016-10-03 07:47:13
您使用了错误的数据类型,请改用整数:
int userNum = 0;
int sum = 0;
do {
printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n");
scanf("%d", &userNum);
sum = sum + userNum;
} while (userNum != 25);
printf("The sum of all the numbers you entered:%d\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
复制相似问题