首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Do While循环的小问题

Do While循环的小问题
EN

Stack Overflow用户
提问于 2016-10-03 07:36:24
回答 3查看 58关注 0票数 0

所以我正在写一个基本的程序,要求用户输入一个数字,循环将继续,直到他们输入一个特定的数字。(25)。然后,程序会将他们输入的所有数字相加。问题是当我输入退出编号时,循环不会退出,并且我不确定原因。

代码语言:javascript
复制
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);

此外,我不确定总和是否会正确计算,因为我从来没有能够退出循环。

EN

Stack Overflow用户

发布于 2016-10-03 08:51:36

你想使用一个前哨控制的循环(25是你的前哨)。以下是我要写的内容:

代码语言:javascript
复制
    #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:

代码语言:javascript
复制
    // 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 main
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39822819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档