c - 使用此复杂逻辑的 switch 语句的意外输出

标签 c switch-statement

我正在尝试对 3 个条件使用 switch 语句。条件是:

  1. 当a、b、c都为零时,x的任意值都是一个解。打印:x 的任何值都是一个解决方案。
  2. 当 a 和 b 为零而 c 不为零时,不存在解。打印:不存在解决方案。
  3. 当 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/

相关文章:

c - 如何在 Rust WASI 中链接 C 库

硬币-文件读取方法中的SPOJ TLE

c++ - 更改版本后降级 g++

java - 带循环开关

C++ Switch 语句大小写错误

c - 如何将if转换为c中的switch-case

c - 如何在 C 中编辑 .csv 文件

c - 将变量分组到 C 中的结构或容器中

javascript - Postman 测试使用 HTTP 状态代码的 switch 语句

java - 使用 Switch 语句创建对象 : Cannot make a static reference to the non-static method?