C程序 - Double返回零

时间:2016-03-20 09:20:33

标签: c double scanf

这是C程序

#include <stdio.h>
#include <stdlib.h>

int main (void){

    double voltage, resistance;
    printf("Enter your Voltage: ");
    scanf("%f", &voltage);
    printf("Enter your Resistance: ");
    scanf("%f", &resistance);
    double amps = voltage / resistance;
    printf("With voltage %f and Ohm %fohms, amps is equal to %f \n", voltage, resistance, amps);
    return 0;
}

为什么电压和电阻变量的返回值为0.00?

2 个答案:

答案 0 :(得分:3)

对于scanf (and family)格式public MathObject add(MathObject that){ if (that instanceof Constant) return add((Constant) that); else that.add((Constant)this); // note that the casting here only makes // sense if MathObject has an add method // that takes a Constant. otherwise is makes // no difference } 适用于"%f",要获得float,您需要具有格式前缀{的{long“double {1}},如float

答案 1 :(得分:2)

您应该在scanf中使用%lf

这对我很好:

#include <stdio.h>
#include <stdlib.h>

int main (void){

double voltage, resistance;
printf("Enter your Voltage: ");
scanf("%lf", &voltage);
printf("Enter your Resistance: ");
scanf("%lf", &resistance);
double amps = voltage / resistance;
printf("With voltage %f and Ohm %fohms, amps is equal to %f \n", voltage, resistance, amps);
return 0;
}