我正在尝试制作欧姆定律程序。 V = 红外。
#include <stdio.h>
int main(int argc, const char * argv[]) {
int V,I,R;
printf("please enter the value of the current if the value is not known make I=0 ");
scanf("%d", &I);
printf("please entre the value of the resistance if the value is not known make R=0");
scanf("%d", &R);
printf("please enter the value of the voltage, if unknown make V=0");
scanf("%d", &V);
if (V == 0)
V = I*R;
{
printf(" V = %d",V);
}
else if (I==0)
I = V/R;
{
printf("I = %d ",I);
}
else
R = V/I;
{
printf("R= %d",R);
}
return 0;
}
我是初学者,如何改进我的代码,使其有效? 非常感谢任何帮助,谢谢。
最佳答案
使用浮点变量:
#include <stdio.h>
int main(int argc, const char * argv[])
{
float V,I,R;
printf("welcome to my lovely program");
printf("please enter the value of the current if the value is not known make I=0 ");
scanf("%f", &I);
printf("please entre the value of the resistance if the value is not known make R=0");
scanf("%f", &R);
printf("please enter the value of the voltage, if unknown make V=0");
scanf("%f", &V);
if (V == 0)
{
V = I*R;
printf(" V = %f",V);
}
else if (I==0)
{
I = V/R;
printf("I = %f ",I);
}
else
{
R = V/I;
printf("R= %f",R);
}
return 0;
}
如果使用 int
而不是 float
或 double
,则除法时会得到截断值。请学会缩进你的代码 - 你的 if-else block 都搞乱了。
关于谁能帮我写一下我的 C 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19197006/