[英]A simple C switch statement program error. I cant build and run it. I don't know why
我是C语言编程的新手,我正在尝试一本书中的一段代码。 当我尝试构建和运行它时,出现错误和警告,提示我无法运行该程序。 不知道为什么。 我的代码是逐字编写的。 我也在PC上使用codeBlocks。
#include <stdio.h>
int main()
{
char choice;
printf("Are you filing a single, joint or ");
printf("Married return (s, j, m)? ");
do
{
scanf(" %c ", &choice);
switch (choice)
{
case ('s') : printf("You get a $1,000 deduction.\n");
break;
case ('j') : printf("You geta 1 $3,000 deduction.\n");
break;
case ('m') : printf("You geta $5,000 deduction.\n");
break;
default : printf("I don't know the ");
printf("option %c.\n, choice");
printf("Try again.\n");
break;
}
}while ((choice != 's') && (choice != 'j') && (choice != 'm');
return 0;
}
该错误是由于While
语句中缺少)
。
当前是: while ((choice != 's') && (choice != 'j') && (choice != 'm');
它应该是
while ((choice != 's') && (choice != 'j') && (choice != 'm'));
除此之外,您的scanf
和printf
语句还有问题。
当前它们是: scanf(" %c, &choice");
和
printf("option %c.\\n, choice");
这些应更改为: scanf(" %c", &choice);
和
printf("option %c.\\n", choice);
如果在编写代码时格外小心,可以轻松避免此类问题。
您有几个语法问题。
在scanf
行中, scanf
双引号放在错误的位置,应该在%c
。
scanf(" %c", &choice);
在while
行中,您在行末缺少左括号。
} while ((choice != 's') && (choice != 'j') && (choice != 'm'));
修复这两个错误会导致程序编译并可以正常运行。
In function 'main':
Line 25: error: expected ')' before ';' token
Line 27: error: expected ';' before '}' token
Line 27: error: expected declaration or statement at end of input
首先,您不必关闭do-while循环的花括号。 您需要在末尾添加大括号。
while ((choice != 's') && (choice != 'j') && (choice != 'm'));
此外,正如其他人提到的那样,您需要将scanf语句更改为
scanf(" %c", &choice);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.