【问题标题】:Can a section of the code be interfering with the loop? [closed]代码的一部分是否会干扰循环? [关闭]
【发布时间】:2012-11-02 03:29:39
【问题描述】:

我正在用 C 编写一个计算器,它可以进行基本算术运算,并且可以循环直到用户输入命令。我以为我掌握了循环的窍门,但我只放了一个循环(开始一项新操作)并且它不起作用。代码的一部分是否会干扰循环?语法错了吗?否则程序运行良好。

int main(int argc, char *argv[])
{
    char reponse;

    int oper;
    float nb1, nb2, resultat;

    do
    {
        printf("Entrez les deux valeurs que vous voulez calculer: \n");
        scanf("%f %f", &nb1, &nb2);

        printf("\nValidez votre op\x82rateur pour effectuer votre cacul\n");
        printf("choisissez \"1\" pour une addition, \"2\" pour une soustraction,\n");
        printf("\"3\" pour une multiplication ou \"4\" pour une division\n");
        scanf(" %d", &oper);

        switch(oper )
        {
            case 1:
                resultat = nb1 + nb2;
                printf("\n%.2f + %.2f = %.2f\n", nb1, nb2, resultat);
                break;
            case 2:
                resultat = nb1 - nb2;
                printf("\n%.2f - %.2f = %.2f\n", nb1, nb2, resultat);
                break;
            case 3: resultat = nb1 * nb2;
                printf("\n%.2f * %.2f = %.2f\n", nb1, nb2, resultat);
                break;
            case 4: resultat = nb1 / nb2;
                printf("\n%.2f / %.2f = %.2f\n", nb1, nb2, resultat);
                break;
            default:
                printf("\nErreur\n");
        }

        printf("\nVoulez-vous continuer \x85 faire des op\x82rations? [o/n]\n");
        scanf(" c%", &reponse);
    } while (reponse == 'o' || reponse == 'O');


    printf("\nMerci au revoir ! Appuyez sur une touche quelconque pour terminer");
    getch();
}

【问题讨论】:

  • c% in scanf 应该是 %c
  • 不,scanf 正在获取 \n 并且不等待用户输入 'o'
  • (当我说“不”时,我的意思是“不,这还不是全部”) - 请参阅下面的答案
  • @iccthedral: aaaaaaaaaaaaaahhhhhhhhhhh 就是这样!谢谢。啊,我真是个笨蛋!!!
  • @Phil Newbie - 实际上有几个问题。你很快就会发现(如果你还没有发现的话)iccthedral 和 William Morris 都是正确的。如果有帮助,请务必支持威廉莫里斯并“接受”他的回答。

标签: c loops do-while


【解决方案1】:

使用

char reponse[4];

....

scanf("%3s", reponse);
} while (reponse[0] == 'o' || reponse[0] == 'O');

【讨论】:

    猜你喜欢
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    相关资源
    最近更新 更多