我在大学的第一学期,在课堂上无法解决计算问题。虽然我已经做了很多研究并尝试了很多方法,但我仍然无法得到正确的结果。我希望有人可以帮助我,因为这是我第一次在Stackoverflow。我正在使用Code Block btw。
要求:
首先,提示用户输入表示电容器C1和C2的两个电容值。
然后程序显示以下菜单:
对于以下内容,您必须使用switch语句。 - 如果输入选项1,2或3,则使用以下公式计算总电容,电压降或电荷:
V = 12 C =(C1 * C2)/(C1 + C2)
V = V1 + V2其中V1 = V *(C / C1)且V2 = V *(C / C1)
Q = Q1 + Q1。
这是我的代码。
#include <stdio.h>
int main (){
char choice;
float c1,c2,ct;
ct =(c1 * c2) / (c1+c2);
printf("Please enter the capacitance value of c1: ");
scanf("%f", &c1);
printf("\nPlease enter the capacitance value of c2: ");
scanf("%f", &c2);
printf("\nPlease enter 1 if you need total capacitance");
printf("\nPlease enter 2 if you need voltage of each resistor");
printf("\nPlease enter 3 if you need electrical charge \n");
scanf("%c", &choice);
switch (choice) {
case 1:
printf("\nThe total capacitance is %.2f", ct);
case 2:
printf("\nThe Voltage drop V1 is %.2f and V2 is %.2f", 12*(ct/c1), 12*(ct/c2));
case 3:
printf("\nThe electrical charge is Q %.2f", 12 * ct );
default:
printf("\nInvalid weekday number.");
}
return 0;
}
答案 0 :(得分:0)
正如@xing在评论中所说,您希望在switch语句中使用case '1':
中的单引号。在C中,1
是整数文字,'1'
是字符文字。单引号基本上导致C将字符转换为其ASCII值,因此它将与scanf
与%c
返回的内容相匹配。但是,因为C中的字符基本上是1字节整数,所以如果你告诉它(通过case
语句)来比较char和整数,你的编译器可能不会抱怨。
您可能还希望在每个break;
的末尾添加case
语句,以便在不执行下一个switch
的情况下突破case
。