[英]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.