C 计算错误

标签 c

我正在尝试编写一个程序来计算简单电路的各种值,但没有一个计算能够提供正确的答案。这就是问题所在:

void input();
void current(double,double,double);
void voltage1(double,double,double);

void input()
{
    double voltage;
    double R1;
    double R2;
    int selection;

    //I'm not entirely sure why the & signs need to be where they are, but the program won't run past here without them.
    scanf("%d",voltage);
    scanf("%d",&R1);
    scanf("%d",&R2);
    selection = menu(); //menu is a separate method that does work for selecting what to calculate.

    switch (selection)
    {
    case 1:
        current(voltage,R1,R2);
        break;
    case 2:
        voltage1(voltage,R1,R2);
        break;
    } //end of switch selection
} //end of input

void current(double voltage,double R1,double R2)
{
    double I = voltage / (R1 + R2);
    printf("%d",I);
} //end of current

void voltage1(double voltage,double R1,double R2)
{
    double V1 = (voltage * R1) / (R1 + R2)
    printf("%d",V1);
} //end of voltage1

使用 10 代表电压,R1 和 R2 应返回 1 代表电流,5 代表电压,但我将始终得到 789577626 代表电流,0 代表电压。电流总是在我得到的 10、5 和 5 的值附近,电压 1 将始终为 0。

最佳答案

您的 scanfprintf 格式说明符与您使用的类型不匹配。 %d 适用于 signed int 类型,但您使用 double。您需要使用 %a%A%e%E%f%F%g%G

关于C 计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28952298/

相关文章:

c - libcurl: ftp 上传的文件名在 # 字符后被截断

c - c 中的 %(modulus) 运算符如何工作?

c - 如何给C中的函数提供参数

本地计算机上的 c 代码很好,但算法预热练习 "angry children"中 hackerrank 的运行时错误?

计算两个日期之间的天数

c - 不正确的二叉树

c - 关于 C struct packing 有什么保证吗?

c - 在 C 上定义 LDBL_MAX/MIN

c - 将文本读入 C。出现错误的执行错误

在树莓派中创建makefile