C编程switch case有什么问题?

标签 c

我必须使用 switch case 编写一个程序,该程序查找一个数字是否小于 10、等于 10、大于 10 和小于 100 并且与上述选项不同。该数字由用户给出。 我试过这个:

#include <stdio.h>
int main ()


switch ( 4*(n >= 100) + 2*(n >= 10) + (n <= 10) )
{
case 1: printf( "%d is less than 10\n", n); break;

case 3: printf( "%d is equal to 10\n", n); break;

case 2: printf( "10 < %d < 100\n", n); break;

default: printf(" %d is not in an identified range\n", n); break;
}

但是当我尝试编译它时,它说:

ERROR IN "switch ( 4*(n >= 100) + 2*(n >= 10) + (n <= 10) ) ".

哪里出错了?我需要在 switch 中写这个。

错误:“switch”之前的 D:\comparison.c 语法错误

最佳答案

如果这是您的准确代码,则以下内容是错误的:

  • main() 声明之后没有左大括号。因此,没有函数body,并且您的代码现在位于全局命名空间的中间。
  • 也没有声明变量n,因此它也会导致编译错误。
  • 最后,main() 没有返回值,这虽然不是编译错误(除非警告足够迂腐),但它是一个逻辑错误,并为 main 留下了返回值() 具有未定义的行为。

这有效:

#include <stdio.h>
int main( int argc, char* argv[] )
{ // <<==== note: added opening curly brace

    int n=65; // <<==== note: added declaration of n

    switch ( 4*(n >= 100) + 2*(n >= 10) + (n <= 10) )
    {
        case 1: printf( "%d is less than 10\n", n); break;
        case 3: printf( "%d is equal to 10\n", n); break;
        case 2: printf( "10 < %d < 100\n", n); break;
        default: printf(" %d is not in an identified range\n", n); break;
    }

    return 0; // <<==== note: added return value
} // <<== note: added closing curly brace

我留下您的 switch 条件中的实际表达式对您来说是否正确(我认为它们不正确,但我不熟悉您的作业)。

关于C编程switch case有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134563/

相关文章:

更改 C 中 char 数组的值

c - 如何使用 C 语言在整个程序中仅使用一个变量接受 5 个数字并打印总和?

c - linux symlink()函数在绝对路径上损坏

c - 执行 free() 时出错,显示 "glibc detected double free or corruption"

c - C 库的实现是否依赖于操作系统?

c - ansi c - 自动清理难看的代码

c - 存储三元值的最紧凑方式是什么?

c - 从 fgets() 输入中删除尾随换行符

c - 在 C (Windows) 中检测 USB 驱动器插入

c - IGMPv2 数据包上的路由器警报选项