【问题标题】:C beginner, code not outputting properlyC初学者,代码输出不正确
【发布时间】: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++,但考虑到您是初学者,这可能只是运气。我建议只标记您正在编写的语言。

标签: c printf output scanf


【解决方案1】:

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

更多详情请看C++ reference

【讨论】:

  • 非常感谢!知道这是一个愚蠢的错误-___-
  • @celeste 在编程时避免使用1l 看起来过于相似的字体。
【解决方案2】:

既然你声称要学习 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";
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2017-06-28
      • 2014-05-04
      相关资源
      最近更新 更多