当我运行这段代码时,一切都会顺利进行到最后一部分。在问“您想重复吗?”之后询问时,控制台不会提示用户输入答案,而是结束编程。
如何编辑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");
}
答案 0 :(得分:2)
上一个输入操作的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
。因此,%f
只有printf()
。
PS: 正如Cacahuete Frito在评论中所说的:
您应该检查
scanf()
的返回值
是的,你应该。永远不要信任用户。