C初学者,代码输出不正确

标签 c printf output scanf

所以我对编码非常陌生,这是我第一次在这种程度上使用 scanf 和 printf。对于我的家庭作业,我们应该创建一个程序来计算每 100 公里的燃油效率(以 mpg 和升为单位)。最终答案应该只有 2 个小数点……但那是另一回事了。 ;P

现在,该程序让我为第一部分输入一个值(多少英里),但是,一旦我点击输入,它就会跳到我的代码末尾并输出一个(看似)随机数?

#include <stdio.h> /* tells computer where to find definitions for printf and scanf */
#define KMS_PER_MILE 1.61 /* conversion constant for miles to kms */
#define LIT_PER_GAL 3.79 /* conversion constant for gallons to liters */

int main(void)
{
    double miles, /* input - distance in miles. */
    gallons, /* input - gallons consumed */
    mpg, /* output - miles per gallon */
    kms, /* output - kilometers */
    liters, /* output - liters */
    lpkm; /* output - liters per 100 kms */

    /* get the distance in miles */
    printf("Enter the distance in miles> ");
    scanf("%1f", &miles);

    /* get the gallons consumed */
    printf("Enter the gallons consumed> ");
    scanf("%1f", &gallons);

    /* convert to mpg */
    mpg = (double)miles / (double)gallons;

    /* convert to lpkm */
    liters = LIT_PER_GAL * gallons;
    kms = KMS_PER_MILE * miles;
    lpkm = (double)liters / (double)kms * 100;

    /* Display fuel efficiency in mpg and lpkm */
    printf("The car's fuel efficiency is\n %1f mpg \n %1f liters per 100 kms", mpg, lpkm);
    return (0);

}

最佳答案

尝试在scanf中将%1f更改为%lf

更多详情请看C++ reference

关于C初学者,代码输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28261168/

相关文章:

c - 在 C 中寻找文件位置 > 2^32

java - 幻方的 Printf

perl - 在 Perl 中将输出写入控制台有哪些不同的方法?

c - Printf 不是 c 语言的一部分。从 stdio.h 执行 PRINTF 的代码时实际发生了什么?

powershell - 如何在Powershell脚本中输出被调用命令的所有输出

php - 如何创建一个空的 op_array?

c - 如何在c中创建符号链接(symbolic link)链

将 ffmpeg 帧转换为 C 中的 YUV 像素数组

java - Eclipse Debug模式: Console output isn't working

R Shiny : Isolate dynamic output within dynamic tabs