[英]Wrap a switch statement inside an if statement C?
所以我希望我的程序在2个值之间进行算术运算:
1.首先,我要我的程序检查输入的两个值是否为数字
2.如果是正确的话,我不希望运行switch语句,该语句取决于操作员来进行计算
3.如果输入的运算符不是有效的(*,+,-,/),那么我不会返回错误,表示该运算符无效
4.如果值不是数字,我将不会显示输入的值无效
例如,如果我输入K * 2,我希望程序说“错误无效值”
如果输入20? 2程序应返回“错误有效的运算符”
我尝试使用{}和()来包装switch函数,但是似乎没有任何效果
#include <stdio.h>
int main (void)
{
float value1, value2;
char Operator;
printf("Enter your two values expression (x (+, -, *, /) y): ");
scanf("%f %c %f", &value1, &Operator, &value2);
if( (value1>=0 && value1<=9) || (value2>=0 && value2<=9) )
switch(Operator)
{
case '+':
printf("The result is: %.2f \n", value1+value2);
break;
case '-':
printf("The result is: %.2f \n", value1-value2);
break;
case '*':
case 'x':
case 'X':
printf("The result of this multiplication is: %.2f \n",
value1*value2);
break;
case '/':
if(value1==0 || value2==0)
printf("Error 1 you can't divide by 0 \n");
else
printf("The result of this division is: %.2f \n", value1/value2);
break;
default:
printf("Error please enter a valid operator \n");
break;
}
else printf("Error please enter a valid value \n");
}
当我输入无效值时,程序将返回“错误,请输入有效的运算符”,而不是else语句“错误,请输入有效值”
同样,如果第一个值正确但第二个值不正确,则说:10 * c而不是返回“ Error,请输入一个有效值”,而是返回0。
正如您输入20 ? 2
时所说的那样20 ? 2
20 ? 2
因为您有if( (value1>=0 && value1<=9) || (value2>=0 && value2<=9) )
,错误将涉及值而不是运算符。 必须删除该值的测试。
您只需要检查scanf的结果
如果为0,则第一个输入的值不是有效的浮点数
如果为1,则仅输入了有效的浮点数,后面没有空格,则运算符
如果是2,则仅是一个有效的浮点数,然后是一个空格,然后输入了操作员;如果操作员没有空格,则是有效的浮点
如果为3,则您知道value1和value2是有效值并输入了运算符,则可以切换到测试运算符并计算结果
代码中的唯一问题,除了缩进和不将某些内容包装在{ }
内(尽管它也应该以这种方式工作)之外,是您输入的数字不正确。
if( (value1>=0 && value1<=9) || (value2>=0 && value2<=9) )
,您仅检查0到9之间的值。如果输入10,则不会工作。 我看到您正在尝试检查字符,例如'0'或'9',但是您需要另一个函数来处理刚刚读入的内容。 ||
代替&&
。 现在,即使只有一个数字有效,测试也会通过。 scanf("%f", ...)
。 假设我在那输入K
计算机将尝试像处理浮点数一样对其进行处理。 我建议使用fgets
,然后使用另一个函数(逐个字符)处理它,以建立数字。 如果有人知道更好的方法,请随时发表评论。 我希望这有帮助。
为简单起见,我将float更改为整数类型。
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int value1, value2;
char Operator;
printf("Enter your two values expression (x (+, -, *, /) y): ");
if (scanf("%d %c %d", &value1, &Operator, &value2) != 3)
{
printf("Either of value1 or value2 is not a number. Enter valid input\n");
return EXIT_FAILURE;
}
switch(Operator)
{
case '+':
printf("The result is: %d \n", value1+value2);
break;
case '-':
printf("The result is: %d \n", value1-value2);
break;
case '*':
case 'x':
case 'X':
printf("The result of this multiplication is: %d \n", value1*value2);
break;
case '/':
if(value2==0)
{
printf("you can't divide by 0, Hence value2 must be an non zero integer\n");
}
else
printf("The result of this division is: %d \n", value1/value2);
break;
default:
printf("Error please enter a valid operator \n");
break;
}
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.