c - Switch 语句执行不止一种情况 - C 编程

标签 c switch-statement

我的代码: 我是一个初学者 - 所以对我要宽松一些 因此,下面代码中的 switch 语句执行了不止一种情况的语句。我似乎找不到问题。一切似乎都是对的。 查看输出图像和我的代码,我需要帮助。

//write a program that acts as a simple "printing" calculator
//enter expressions in the format "operator number"
//include operators to 'set accumulator' and 'end execution'
#include<stdio.h>
int main()
{
 float number, accumulator;
 char operator;

 printf("Begin Calculations: (Enter 'S' operator to set the accumulator and 'E' operator to end execution)\n");
 printf("-------------------\n\n");

 while(operator != 'E')
 {
  scanf("%c%f", &operator, &number);
  switch(operator)
  {
   case 'S':
     accumulator = number;
     break;
   case '+':
     accumulator += number;
     break;
   case '-':
     accumulator -= number;
     break;
   case '*':
     accumulator *= number;
     break;
   case '/':
     accumulator /= number;
     break;
   case 'E':
     printf("End of Calculations.\n");
     break;
   default:
     printf("Enter proper Expression.\n");
     break;
  }
  printf("= %f\n", accumulator);
 }

 return 0;
}

click for output:

最佳答案

scanf 返回一个整数,指示从格式说明符成功分配的变量数。

您没有检查 scanf 的返回值,而是继续使用您希望它赋值的变量。这始终是一个错误。

scanf 可能失败,并且您的循环将继续使用 operator 的先前值。

您应该检查,在这种情况下,scanf 返回 2。否则,它没有获得有效的输入,并且您的变量没有更改。

关于c - Switch 语句执行不止一种情况 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694163/

相关文章:

c# - 你如何处理对象类型切换?

Java 12 intellij 开关表达式不起作用

java - 使用 switch case 检查用户输入是字符串、整数还是 float

java - 如何消除 switch case 或 if-else ?并执行以下操作?

CUDA:车道之间的 __shfl delta 可以不同吗?

c - float 数组没有得到正确的大小——C

c - 使用结构和 malloc 时为 "error: conversion to non-scalar type requested"

switch-statement - Latex 中的 Switch Case 条件输出

c - C中以void指针为值的Hashmap实现问题

c - 二维数组以错误的方式打印