【发布时间】:2015-02-18 06:28:09
【问题描述】:
作为 c 编程的新手(我只有 Visual Basic 方面的经验),我不完全确定在其条件语句中使用不断变化的字符串变量的 while 循环应该如何运行。
下面的代码是我正在制作的一个简单的计算器,它允许用户输入一个操作和两个数字,然后输出相应的结果。我正在尝试在一个while循环中编写代码,该循环不断重复该过程,直到用户决定退出它。然而,似乎这行 scanf("%c", &quit);不影响 while 循环条件语句。
#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = "n";
while (quit = "n"){
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
switch(operation) {
case '+':
printf("%f\n", num1+num2);
break;
case '-':
printf("%f\n", num1-num2);
break;
case '*':
printf("%f\n", num1*num2);
break;
case '/':
printf("%f\n", num1/num2);
break;
}
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
}
return 0;
}
提前感谢您的所有帮助。
【问题讨论】:
-
char quit = "n";不是 C。 -
了解单引号和双引号的区别
-
启用所有编译器警告,并注意它们。
-
肯定会阅读差异,目前在程序中使用整数作为是和否选项,似乎工作正常,但一旦我了解更多,就会修改它。谢谢大家的帮助,我真的很感激:)
-
@twalberg - 我的所有编译器警告都已启用,它们确实有助于确保我不会错过任何愚蠢的事情。不过,这段代码似乎没有发现任何问题。
标签: c string while-loop