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

C beginner, code not outputting properly

所以我对编码很陌生,这是我第一次在这种程度上使用 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++的,如果你用过C++标准库就可以避免这个问题了:

#include <iostream> // std::cin, std::cout

int main()
{
  std::cout << "Enter the distance in miles> ";
  std::cin >> miles;
  std::cout << "Enter the gallons consumed> "
  std::cin >> gallons;
  ....

  std::cout << "The car's fuel efficiency is\n" << mpg << "\n" 
            <<  lpkm << " per 100 kms\n";
}

对于打印,您可以使用 1f 但在输入期间您必须使用 lf .