首页 > 解决方案 > 如何修复这个 do-while 循环,以便控制台程序在自动关闭之前提示用户?

问题描述

当我运行这段代码时,一切都运行顺利,直到最后一部分。在“你想重复一遍吗?”这个问题之后 被询问时,控制台不会提示用户回答,而是结束编程。

如何编辑 do-while 循环的代码,以便提示用户回答而不是自动关闭程序?我觉得这是格式说明符的问题,我对此很陌生,并且一直对此有疑问。谢谢!

#include <stdio.h>

int main(void)
{
    double num1, num2;
    char operation, repeat = "y";
    printf("This is a calculator.");

    do {
        printf("\nWould you like to multiply(*), divide(/), add(+) or subtract(-) the two numbers you will soon input? \n");
        scanf("%c", &operation);
        printf("Please enter the first number you would like to deal with. \n");
        scanf("%lf", &num1);
        printf("And the second?\n");
        scanf("%lf", &num2);

        switch (operation)
        {
        case '*':
            printf("The product of %1.2lf and %1.2lf is %1.2lf.\n",
                   num1, num2, num1 * num2);
            break;
        case '/':
            printf("The quotient of %1.2lf and %1.2lf is %1.2lf.\n",
                   num1, num2, num1 / num2);
            break;
        case '+':
            printf("The sum of %1.2lf and %1.2lf is %1.2lf.\n",
                   num1, num2, num1 + num2);
            break;
        case '-':
            printf("The difference of %1.2lf and %1.2lf is %1.2lf.\n",
                   num1, num2, num1 - num2);
            break;
        }
        printf("Would you like to repeat?(y/n)\n");
        scanf("%c", &repeat);
    } while (repeat == "y" || repeat == "Y");
}

标签: ccalculatordo-whilerepeat

解决方案


stdin前一个输入操作留下了一个换行符。您的

scanf("%c",&repeat);

读取该换行符,因为转换说明符%c不跳过空白字符。利用

scanf(" %c", &repeat);

跳过前导空格。


在 C 和 C++ 中,单个字符用单引号括起来。

char ch;
ch == "A";

会将 的值ch与字符串文字的地址进行比较"A"

所以 ...

while(repeat=="y"||repeat=="Y");

~>

while(repeat == 'y' || repeat == 'Y');

char operation, repeat="y";

~>

char operation, repeat = 'y';

你的编译器应该已经警告你了。如果不是,您应该提高编译器的警告级别。


您可能还想检查未定义的除以零。


最后一件事:printf()不关心 中的长度说明符l%lf这与%f默认参数传播相同。调用带有float可变数量参数的函数中的参数总是double在传递给函数之前转换为。所以只有%ffor printf()


PS:正如Cacahuete Frito在评论中所说:

您应该检查的返回值scanf()

是的你应该。永远不要相信用户。


推荐阅读