【问题标题】:What is wrong with this C code for a simple calculator program?这个 C 代码对于一个简单的计算器程序有什么问题?
【发布时间】:2019-11-26 08:06:29
【问题描述】:

这是我用 C 语言编写的一个简单计算器的代码。
它编译并运行,但不接受字符,只执行默认语句。

#include <stdio.h>

int main() {
    float num1,num2;
    char myOperator;

    printf("Enter two numbers and an operator (a,b,c,d for addition, subtraction, multiplication and division respectively) \n");
    scanf("%f%f%c", &num1, &num2, &myOperator);

    switch(myOperator) {
        case 'a': printf("%f", num1+num2);
        break;

        case 'b': printf("%f", num1-num2);
        break;

        case 'c': printf("%f", num1*num2);
        break;

        case 'd': printf("%f", num1/num2);
        break;

        default: printf("You did not follow the instructions");
        break;
    }

}

【问题讨论】:

  • %f%f%c ==> %f %f %c
  • 第一件事,总是检查返回值。你给它什么输入字符串,如果你打印 num1、num2 和 myOperator 会显示什么?

标签: c calculator


【解决方案1】:

它确实接受char,只是它将第二个float 之后的空格作为char。如果您尝试在第二个float 之后输入没有任何空格的输出,这一点就会变得很明显,例如2 3c。

您可以通过在格式字符串中添加空格来跳过第二个浮点数之后的所有空格,如下所示:

scanf("%f%f %c", &num1, &num2, &myOperator); // note the space before the "%c"

这样您就可以像2 3 c 这样输入您的输入,它将以'c' 作为字符,而不是'3' 和'c' 之间的空格。

您可以阅读此行为here:

空白字符:格式中的任何单个空白字符 string 使用所有可用的连续空白字符 输入(好像通过在循环中调用isspace 来确定)。注意 "\n"、" "、"\t\t" 或其他空格之间没有区别 在格式字符串中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多