c - 计算不正确

标签 c

伙计们,我是编程和 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/

相关文章:

php - php-cpp 是否适用于 C 库?

c - PQunescapeBytea() 为 E'\n'::bytea 返回类似 "x0a"的字符串

c - C函数中的指针到指针;链表

c - 将结构写入 .dat 文件

c - 优雅的宏 if block

c++ - 面试题: Trim multiple consecutive spaces from a string

c - 从 Dcache (L1) 读取值与全局变量

c - 使用 C 建立与 RS232 的串行连接

c - 如何提高帧速率并减少 C 中的闪烁?

c - 如何从开罗表面创建 GtkImage?