我正在尝试对 3 个条件使用 switch 语句。条件是:
- 当a、b、c都为零时,x的任意值都是一个解。打印:x 的任何值都是一个解决方案。
- 当 a 和 b 为零而 c 不为零时,不存在解。打印:不存在解决方案。
- 当 a 为零且 b 不为零时,唯一的解决方案是 x = -c/b。计算 x 的值并打印解决方案。
当我尝试运行我的程序时,它显示了错误的结果。我的输入是
a = 0
b = 0
c = 0
所以它应该打印“任何 x 的值都是一个解决方案”,但它没有。
我的程序是:
#include <stdio.h>
//Function declarations
void getData (int* a, int* b, int* c);
float calculateX (int a, int b, int c);
//===================================================
int main (void)
{
//Local declarations
int a;
int b;
int c;
float x;
//Statements
getData (&a, &b, &c);
calculateX (a, b, c);
int temp;
printf("\nEnter an integer and press enter to exit the program: ");
scanf("%d", &temp);
return 0;
}
//----------------------------------------------------
void getData (int* a, int* b, int* c)
{
printf("Enter three integers: ");
scanf("%d %d %d", a, b, c);
return;
}
//----------------------------------------------------
float calculateX (int a, int b, int c)
{
float x;
printf("Input is: %d %d %d\n", a, b, c);
switch(a, b, c)
{
case 1: (a, b, c == 0);
printf("Any value of x is a solution.");
break;
case 2: (a, b == 0 && c!= 0);
printf("No solution exists.");
break;
case 3: (a == 0 && b!= 0);
x = (float)(-c/b);
printf("The value of x is: %.1f", x);
break;
default: printf("Cannot calculate.");
}
return a, b, c;
}
我的输出是:
Enter three integers: 0 0 0
Input is: 0 0 0
Cannot calculate.
Enter an integer and press enter to exit the program:
最佳答案
这不是 switch
语句的工作方式。它编译,但出于非常模糊的原因。显然,它在运行时并没有达到您的预期。
一般来说,您在单个 表达式上使用switch
语句,每个case
标签代表该表达式的一个可能值.例如:
switch (x)
{
case 1:
// Code here runs when x == 1
break;
case 2:
// Code here runs when x == 2
break;
default:
// Code here runs for all other values of x
break;
}
在您的应用程序中,您想要测试多个变量,并以复杂的方式组合它们。使用 switch
没有巧妙的方法来做到这一点。您应该考虑使用一组 if
语句。
关于c - 使用此复杂逻辑的 switch 语句的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6117803/