【发布时间】:2015-02-01 09:10:43
【问题描述】:
所以我对编码非常陌生,这是我第一次在这种程度上使用 scanf 和 printf。对于我的家庭作业,我们应该创建一个以 mpg 和每 100 公里升数为单位计算燃油效率的程序。最终答案应该只保留 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);
}
【问题讨论】:
-
你的标题说你是C++初学者,你的代码是纯C的。
-
return不是函数,去掉括号。而在 C++ 中,分别从 C99 开始,您可以在main中将return 0;关闭,这是隐含的(但仅存在于此)。此外,虽然此代码是有效的 C 和有效的 C++,但考虑到您是初学者,这可能只是运气。我建议只标记您正在编写的语言。