gpt4 book ai didi

c - 我们需要在 switch 语句后面添加一些东西吗

转载 作者:行者123 更新时间:2023-11-30 21:05:22 25 4
gpt4 key购买 nike

我是 C 语言的初学者。这是我的 C 计算器的代码,但在 switch 语句处出现错误,在 switch 语句开始的行显示“expected () before {”。代码如下:

int main()
{
double num_1 = 0.0;
double num_2 = 0.0;
double n = 0.0;
double Total = 0.0;

printf("\nEnter 1 for add:\n ");
printf("Enter 2 for subtract:\n ");
printf("Enter 3 for division:\n ");
printf("Enter 4 for multiplication:\n ");
printf("Enter 5 for percentage:\n ");
printf("Enter 6 for power:\n ");
scanf("%d", & n);

printf("Enter first number: ");
scanf("%d", & num_1);
printf("Enter second number: ");
scanf("%d", & num_2);

switch {
case 1 : Total=num_1+num_2;
printf("The add is : %d\n",Total);
break;
case 2 : Total=num_1-num_2;
printf("The Subtract is : %d\n",Total);
break;
case 3 : Total=num_1/num_2;
printf("The division is : %d\n",Total);
break;
case 4 : Total=num_1*num_2;
printf("The multiplication is : %d\n",Total);
break;
case 5 : Total=num_1%num_2;
printf("The percentage is : %d\n",Total);
break;
case 6 : Total=; pow(num_1, num_2)
printf("The power is : %d\n",Total);
break;
default:
printf("No Result\n");
break;
}

return 0;

}

最佳答案

... is giving me error at the switch statement saying "expected () before {"

这是因为该行

switch {

必须是

switch (n) {

其他一些评论:

1) 在

 double num_1 = 0.0;
double num_2 = 0.0;
double n = 0.0;
double Total = 0.0;

初始化是无用的,因为您将(尝试)在之后重新分配变量

由于使用n,其类型应更改为整数

2) 在

scanf("%d", & num_1);
....
scanf("%d", & num_2);

%d 表示您输入一个 int 但您给出一个指向 double 的指针,这是无效的

例如将 %d 替换为 %g

3) 在

 printf("The add is : %d\n",Total);
...
printf("The Subtract is : %d\n",Total);
...
printf("The division is : %d\n",Total);
...
printf("The multiplication is : %d\n",Total);
...
printf("The percentage is : %d\n",Total);
...
printf("The power is : %d\n",Total);

格式%d意味着你打印一个int但你给出一个double,将%d替换为例如%g

4) 在

case 6 : Total=; pow(num_1, num_2)

“,”位置错误,必须是

case 6 : Total= pow(num_1, num_2);

5) 你不检查是否会除以 0 或对 0 取模

6) 您不会检查 scanf 返回 1,因此是否输入了有效值(也不是 EOF)

7) printf("No Result\n"); 可以替换为 printf("Invalid command\n");puts("无效命令");

关于c - 我们需要在 switch 语句后面添加一些东西吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com