所以我对编码非常陌生,这是我第一次在这种程度上使用 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/