谁能帮我写一下我的 C 代码吗?

标签 c if-statement floating-point scanf

我正在尝试制作欧姆定律程序。 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 而不是 floatdouble,则除法时会得到截断值。请学会缩进你的代码 - 你的 if-else block 都搞乱了。

关于谁能帮我写一下我的 C 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19197006/

相关文章:

mysql - 在c中将文件流传输到mysql

c - 使用缓冲区溢出漏洞运行自己的代码

c++ - 缩短 If 语句并减少冗余

ruby - 带整数的 ZeroDivisionError 异常,带 float 的 Nan

c++ - 如何在 C++ 中将精确的浮点值保存和恢复到人类可读文件

c - 在多个 C 模块之间传递大数组

c - 链接 CUDA 运行 fastHOG 算法的问题

javascript - 仅在小屏幕上显示 div

matlab - 在 MATLAB 中使用 if 语句组合另外两个矩阵来创建新矩阵

c# - 在 C# 中避免数字格式中的额外零