gpt4 book ai didi

c - 如何解决错误: else without a previous if

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

我已经尝试解决这个错误半个小时了。我如何让这段代码工作?

输入完毕,请指出错误。

#include <stdio.h>
#include <math.h>

void main()
{
const float pi = 3.142;
int choice;
float radius, volume, volts, ohms, watts, mass, accel, force;

printf("\n1. Calculate the volume of a sphere");
printf("\n2. Calculate the power of a circuit");
printf("\n3. Calculate the force of an object");
printf("\n-----------------------------------\n");
printf("What is your choice? : ");
scanf("%d", &choice);

if(choice==1)
printf("Enter value of radius (cm) : ");
scanf("%f", &radius);
volume = 4/3 * pi * pow(radius,3);
printf("Volume of a sphere is %.2f", volume);
else if(choice==2)
printf("Enter value of voltage (volts) : ");
scanf("%f", &volts);
printf("Enter value of resistance (ohms) : ");
scanf("%f", &ohms);
watts = pow(volts,2) / ohms;
printf("Power of circuit is : %.2f watts", watts);
else if(choice==3)
printf("Enter mass of object (kg) : ");
scanf("%f", &mass);
printf("Enter acceleration (meters per second squared) : ");
scanf("%f", &accel);
force = mass * accel;
printf("The force of the object is : %.2f Neutons", force);
else
printf("You've entered an invalid choice...");
getch();
}

最佳答案

如果 if/else block 有多行,请使用大括号:

if (choice==1) {
printf("Enter value of radius (cm) : ");
scanf("%f", &radius);
volume = 4/3 * pi * pow(radius,3);
printf("Volume of a sphere is %.2f", volume);
} else if (choice==2) {
printf("Enter value of voltage (volts) : ");
scanf("%f", &volts);
printf("Enter value of resistance (ohms) : ");
scanf("%f", &ohms);
watts = pow(volts,2) / ohms;
printf("Power of circuit is : %.2f watts", watts);
} else if (choice==3) {
printf("Enter mass of object (kg) : ");
scanf("%f", &mass);
printf("Enter acceleration (meters per second squared) : ");
scanf("%f", &accel);
force = mass * accel;
printf("The force of the object is : %.2f Neutons", force);
} else printf("You've entered an invalid choice...");

如果没有大括号,您的代码将被解释为

// Standalone if block
if (choice==1)
printf("Enter value of radius (cm) : ");
// End of the if block
// ...
// else without previous if (syntax error)
else if (choice==2)
printf("Enter value of voltage (volts) : ");

关于c - 如何解决错误: else without a previous if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32548895/

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