gpt4 book ai didi

c - switch语句使用错误: the program takes the value it's not supposed to accept

转载 作者:行者123 更新时间:2023-11-30 20:57:07 25 4
gpt4 key购买 nike

这是一个初学者问题,旨在了解我使用 switch 语句可能会出错的地方。任务如下:编写一个程序,接受用户输入的两个整数值。显示第一个整数除以第二个整数的结果,精确到小数点后三位。请记住让程序检查是否被零除。

为了测试第二个操作数是否为 0,我使用了 switch 语句(我知道我可以使用 if...else 来做到这一点)。但是,程序仍然接受 0 作为操作数,我不确定为什么会发生这种情况。如果它尝试计算除以 0 的结果,程序就会失败。您能给我一个提示,告诉我我可能错在哪里吗?我的代码如下:

  #include <stdio.h>

int main (void)

{
int a, b;


printf ("Type two integer values: ");
scanf ("%i %i", &a, &b);

switch (a/b)
{

case 'b == 0':
printf ("\n The divisor can't be 0.\n");

break;

default:
printf ("The result of dividing %i by %i is %.3f\n", a, b,(float) a / b);

break;
}
return 0;

}

感谢您的帮助!

最佳答案

 switch (b)
{
case 0:
printf ("\n The divisor can't be 0.\n");

break;
default:
printf ("The result of dividing %i by %i is %.3f\n", a, b,(float) a / b);
break;
}

另请注意,case 后面的表达式必须是常量,例如:

case 0:
case 1:
case 'a':
case 'b':

等等

那里..应该解决它。

关于c - switch语句使用错误: the program takes the value it's not supposed to accept,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com