我正在尝试编写一个程序来计算简单电路的各种值,但没有一个计算能够提供正确的答案。这就是问题所在:
void input();
void current(double,double,double);
void voltage1(double,double,double);
void input()
{
double voltage;
double R1;
double R2;
int selection;
//I'm not entirely sure why the & signs need to be where they are, but the program won't run past here without them.
scanf("%d",voltage);
scanf("%d",&R1);
scanf("%d",&R2);
selection = menu(); //menu is a separate method that does work for selecting what to calculate.
switch (selection)
{
case 1:
current(voltage,R1,R2);
break;
case 2:
voltage1(voltage,R1,R2);
break;
} //end of switch selection
} //end of input
void current(double voltage,double R1,double R2)
{
double I = voltage / (R1 + R2);
printf("%d",I);
} //end of current
void voltage1(double voltage,double R1,double R2)
{
double V1 = (voltage * R1) / (R1 + R2)
printf("%d",V1);
} //end of voltage1
使用 10 代表电压,R1 和 R2 应返回 1 代表电流,5 代表电压,但我将始终得到 789577626 代表电流,0 代表电压。电流总是在我得到的 10、5 和 5 的值附近,电压 1 将始终为 0。
最佳答案
您的 scanf
和 printf
格式说明符与您使用的类型不匹配。 %d
适用于 signed int
类型,但您使用 double
。您需要使用 %a
、%A
、%e
、%E
、%f
、%F
、%g
或 %G
。
关于C 计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28952298/