作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经尝试解决这个错误半个小时了。我如何让这段代码工作?
输入完毕,请指出错误。
#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/
我是一名优秀的程序员,十分优秀!