-5

我正在尝试制作欧姆定律程序。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;
}

我是初学者,如何改进我的代码,让它工作?任何帮助都非常感谢,谢谢。

4

4 回答 4

1

使用浮点变量:

#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;
}

如果你使用intand not floator ,你将在除法时得到截断的值double。请学会缩进你的代码——你的 if-else 块都搞砸了。

于 2013-10-05T11:01:58.127 回答
1

您需要学习缩进,并且应该在 if /else if /else 块中给出语句

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);
}

让你所有的声明都浮动,因为你在计算 I 和 R 时除以第二和第三,因为整数你只会得到整数部分。

于 2013-10-05T11:04:30.917 回答
0

尽管您可以使用不带括号的 if 语句编写决策,但您所做的(在 if 语句后添加决策,然后放置括号,然后添加另一个决策)在 C 中是不正确的语法。通常,我总是将决策放在 if or else 括号内的语句,因为它使您和其他人更容易阅读和编辑您的代码。因此,要使其工作,请根据上述解释执行以下操作

#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;
}

然而,这只适用于整数,所以如果我是你,我会使用浮点数或双精度数据类型(尽管不要一直使用双精度数据类型,因为它使用的内存比浮点数多,而且你真的不需要一个小数点太多的数字。还有为什么你把参数放在 int main 函数中,即使你一次都不使用它们?

于 2013-10-05T12:21:10.180 回答
0

首先 - 如果在“if”条件内有超过 1 行要执行,则如果条件跟在括号后面,因此您应该将第一行放在括号内的 if 条件之后,而不仅仅是打印语句。所有条件语句都相同像 elseif 一样使用

于 2013-10-05T11:40:43.737 回答