伙计们,我是编程和 C 语言的新手,学习它只是为了好玩 :) 所以 Currnt 的计算非常正确,它可以计算 4/2 但当我尝试 6/15 时它只回答 0 ,知道为什么吗?
#include <stdio.h>
int main () {
int Volt,Resst;
float Currnt;
printf("Enter the value of resistor:");
scanf("%d",&Resst);
printf("Enter the voltage of power supply:");
scanf("%d",&Volt);
if (Volt > 10)
printf("The voltage is too big\n");
else if (0 > Volt)
printf("Not a valid input\n");
else {
Currnt=Volt/Resst;
printf("The current is %.2f A\n",Currnt);
}
}
最佳答案
如果 if/else 语句 block 包含多于 1 个命令(如上一个 else 分支),则需要使用大括号:
if (Volt > 10)
printf("The voltage is too big");
else if (0 > Volt)
printf("Not a valid input");
else {
Current=Volt/Rest;
printf("...");
}
为避免此类错误,始终使用大括号被认为是最佳实践,即使一个 block 中只有一个命令也是如此:
if (Volt > 10) {
printf("The voltage is too big");
}
else if (0 > Volt) {
printf("Not a valid input");
}
else {
Current=Volt/Rest;
printf("...");
}
更新
在 C/C++ 中,表达式结果的类型(在你的情况下是除法)完全基于其中变量的类型。
在您的情况下,表达式是 int/int
,因此结果将被视为 int
- 您存储的变量类型无关紧要。
解决方案是将至少一个表达式变量显式转换为 float
:
Currnt = (float)Volt/Resst;
或
Currnt = Volt/(float)Resst;
或
Currnt = (float)Volt/(float)Resst;
关于c - 计算不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935238/