【发布时间】:2022-11-25 03:45:19
【问题描述】:
我有一个开关,我想将其嵌套在一个循环中,该循环由从用户收到的变量进行计数器控制。但是,当我将用户值放入循环中时,它会在 1 次迭代后退出。当我在 for 循环的标题中手动放置一个整数值时,它工作得很好......是导致错误的变量计数吗?
这是我的代码:
int main()
{
int i = 0, cost, count, tennis = 18000, Badminton = 14000, Swimming = 16000,
total_cost = 0;
int swim_count = 0, tennis_count = 0, Badminton_count = 0;
char sports_event, name[30];
printf("How many persons are in your party: ");
scanf("%d", &count);
for (i = 0; i < count; i++)
{
printf("\nEnter customer name: ");
scanf("%s", name);
printf(
"\nWhat event would you like to partake in?"
"\n'T' FOR Tennis 'B' for Badminton and 'S' for Swimming: ");
scanf("%c", &sports_event);
switch (sports_event)
{
case 'T':
cost = 18000,
total_cost = total_cost + tennis;
tennis_count = tennis_count + 1;
printf("\nCustomer name: %s", name);
printf("\nEvent type: Tennis");
printf("\nThe even cost is $%d\n", cost);
break;
case 'B':
cost = 14000;
total_cost = total_cost + Badminton;
Badminton_count = Badminton_count + 1;
printf("\nCustomer name: %s", name);
printf("\nEvent type: Badminton");
printf("\nThe even cost is $%d\n", cost);
break;
case 'S':
cost = 16000;
total_cost = total_cost + Swimming;
swim_count = swim_count + 1;
printf("\n Customer name: %s", name);
printf("\n Event type: Swimming");
printf("\n The even cost is $%d\n", cost);
break;
default:
printf("SPORTS EVENT IS INVALID... PLEASE TRY AGAIN\n");
}
}
return 0;
}
【问题讨论】:
-
在对您的代码应用基本格式后,很明显它是不完整的。请发布编译的Minimal, Reproducible Example,或者以其他方式产生您需要帮助才能理解的明确警告/错误。
-
for (i = 0; i <= count; i++)将迭代count + 1次。 -
scanf("%s", &sports_event);尝试将 string 读入单个char。至少,使用scanf(" %c", &sports_event);来读取单个字符。注意 consume optional whitespace 的前导空格。考虑使用fgets来处理输入行。
标签: c loops switch-statement