【问题标题】:Creating a simple calculator in C using switch-statement [closed]使用 switch 语句在 C 中创建一个简单的计算器
【发布时间】:2017-01-22 05:36:43
【问题描述】:

我是 C 编程的初学者,我刚刚在我的代码中使用 if-else 语句制作了一个计算器。现在我尝试使用 switch 语句做同样的事情,但它总是执行默认值。请查看我的代码并建议我出了什么问题。 我目前正在 CodeBlock 中编写代码。

int main()
{
    printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n");
    float num1;
    printf("Please enter the first number: ");
    scanf("%f", &num1);
    float num2;
    printf("Please enter the second number: ");
    scanf("%f", &num2);
    char myChar;
    scanf("%c", &myChar);
    switch (myChar)
    {
        case 'A':
            printf("The addition of %.2f and %.2f is %.2f", num1, num2, num1 + num2);
            break;
        case 'B':
            printf("The subtraction of %.2f and %.2f is %.2f", num1, num2, num1 - num2);
            break;
        case 'C':
            printf("The multiplication of %.2f and %.2f is %.2f", num1, num2, num1 * num2);
            break;
        case 'D':
            printf("The quotient of %.2f and %.2f is %.2f", num1, num2, num1 / num2);
            break;
        default :
            printf("You enterned incorrect input");
            break;
    }
    return 0;
}

任何帮助将不胜感激

【问题讨论】:

  • char myChar; scanf("%c", &myChar); 移动到float num1;之前
  • 当您scanf("%c", &myChar) 时,您正在阅读第二个号码后留下的换行符。你的 switch() 没有这种情况,所以它运行默认值。
  • 不要使用scanf 进行用户输入;使用fgets
  • 无法正确执行是一个绝对无用的错误描述,除非您解释无法正确执行是什么意思。您发布的代码有什么具体问题
  • C scanf() issues?的可能重复

标签: c scanf


【解决方案1】:

您的问题主要与 scanf 相关,即先前输入中剩余的 \n 被解释为该输入的输入。

另外,您的操作提示与其对应的输入不匹配。

建议修复:

float num1;
printf("Please enter the first number: ");
scanf("%f", &num1);

float num2;
printf("Please enter the second number: ");
scanf("%f", &num2);

printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n");
char myChar;
scanf(" %c", &myChar);

您可以添加 printf 作为调试目的 - 这也会有所帮助。第一个输入示例:

float num1;
printf("Please enter the first number: ");
scanf(" %f", &num1);
printf("num1 = %f\n", num1 );

【讨论】:

  • " ""%f" 之前是多余的。
  • @melpomene my bad "%f" 会跳过空格本身..
猜你喜欢
  • 1970-01-01
  • 2019-06-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多