【问题标题】:While loop - changing string variableWhile 循环 - 更改字符串变量
【发布时间】: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


【解决方案1】:

你可以这样做

#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = 'n';
//while (quit = "n") //
  while (quit!= 'y')
 {
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;
}

【讨论】:

    【解决方案2】:

    将while (quit = "n") 替换为while (quit! = 'y')

    【讨论】:

      【解决方案3】:

      这是因为您在 while 循环中分配了退出变量的值,而不是检查它的值。

      将 == 用于 =

      while(quit == "n"){...}
      

      【讨论】:

      • 虽然运营商的选择肯定是错误的,但这也不对。您不能以这种方式将单个字符与静态字符串文字进行比较,并期望从中得到任何有意义的东西......
      • 感谢您的帮助,这么简单的错误,甚至都不知道检查值有不同的操作, - 就像在 Visual Basic 中一样,一个等号似乎可以完成这两个功能 - 。
      • 这个答案确实解决了我遇到的问题,我认为反对票仅仅是因为在单个字符上使用了双引号而不是单引号。
      猜你喜欢
      • 2022-07-07
      • 2013-09-13
      • 1970-01-01
      • 2020-05-22
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      相关资源
      最近更新 更多