【问题标题】:C Program - Double returns zero [duplicate]C程序 - 双返回零[重复]
【发布时间】:2016-07-06 20:08:04
【问题描述】:

这是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?

【问题讨论】:

  • 嘿,谢谢,你能解释一下添加“l”的作用吗?
  • 你可能想在scanf()上进行RTFM:iso-9899.info/n1570.html#6.2.5p28
  • 你的编译器应该警告格式说明符和传递的参数类型不匹配。如果不增加其警告级别。认真对待警告。
  • OT:您的结果字符串缺少电压和电流单位,以及输入提示。电阻的单位不是“ohms”而是“Ohm”,简称Ω。

标签: c double scanf


【解决方案1】:

对于scanf (and family)"%f" 的格式是float,要获得double,您需要一个“长”float,其格式前缀为l,如"%lf"


应该注意,对于使用printf 打印浮点值,所有float 参数都将提升double。这意味着对于printf%f%lf 之间没有区别。

【讨论】:

    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 2021-12-12
      • 2016-05-30
      • 2016-04-17
      相关资源
      最近更新 更多