【问题标题】:C program will not divide two scanf inputs correctlyC程序不会正确划分两个scanf输入
【发布时间】:2019-09-30 16:55:13
【问题描述】:

我正在尝试创建一个程序,该程序接受用户使用的加仑数和行驶里程数的三个油箱的输入,以完成一项任务。我遇到的问题是 for 循环要么没有正确地将输入中处理的两个值划分为第三个值(每加仑平均英里数),要么程序没有正确处理输入。但是我对此仍然很陌生,所以我不确定问题出在哪里。


    for(i = 1; i <= 3; ++i)
    {
        /* Define calculations */
        /* ------------------- */

        ave_miles = miles / gallons;
        total_miles = total_miles + miles;
        total_gallons = total_gallons + gallons;
        total_ave_miles = total_miles / total_gallons;

        /* Propmpt user for miles and gallons used and calculate miles per gallon. */
        /* ----------------------------------------------------------------------- */

        printf("Enter the number of gallons used for Tank #%i: ", i);
        scanf("%f", &gallons);
        while ( (c = getchar() != '\n') && c != EOF);

        printf("Enter the number of miles driven: ");
        scanf("%f", &miles);
        while ( (c = getchar() != '\n') && c != EOF);

        printf("*** The miles per gallons for this tank is %.1f\n\n", ave_miles);
    } /* end for loop */

    /* Display and calculate the total miles per gallon for the three tanks. */

    printf("Your overall average of miles per gallon for three tanks is %.1f\n\n", total_ave_miles);
    printf("Thank You for using the program. Goodbye.\n");

} /* end main */

【问题讨论】:

  • 欢迎来到 Stack Overflow!请edit您的代码将其减少为您的问题的minimal reproducible example。您当前的代码包含许多与您的问题无关的内容 - 一个最小样本通常看起来类似于一个好的单元测试:只执行一项任务,并为可重复性指定输入值。
  • 关于; /* Define calculations */ /* ------------------- */ ave_miles = miles / gallons; total_miles = total_miles + miles; total_gallons = total_gallons + gallons; total_ave_miles = total_miles / total_gallons; 这些可执行语句有误。它们应该是 cmets,而不是可执行代码。
  • 这两个语句:while ( (c = getchar() != '\n') &amp;&amp; c != EOF); 不需要,因为输入格式说明符%f 将占用前导“空白”
  • 旁白:您不需要此处的换行删除代码。 scanf 的大多数格式说明符会自动过滤前导空格,因此您只需要两个 scanf 语句即可。例外是 %c%[]%n
  • 一般来说,在变量被初始化/分配一些值之前,不能对变量执行数学运算

标签: c for-loop scanf division


【解决方案1】:

C 和 C++ 没有惰性求值。所以如果你这样做:

ave_miles = miles / gallons;
scanf("%f", &miles);
scanf("%f", &gallons);
printf("%f\", ave_miles);

它不会给你miles / gallons 的平均值。

相反,第一行会将miles / gallons 的除法分配为这些变量在特定时刻的值(即0.0 / 0.0,这将产生一个不是数字NaN)。

你想这样做:

scanf("%f", &miles);
scanf("%f", &gallons);
ave_miles = miles / gallons;
printf("%f\", ave_miles);

现在,miles / gallons 除法将为您提供这些变量所持有的平均值。

【讨论】:

  • 谢谢,这解决了这个问题。那么对于我的蓄能器,我是否也会移动它们?
  • 是的。你对他们做同样的事情。该程序按顺序运行。每个像a=b 这样的命令都会使a 获得b 的当前值。
猜你喜欢
  • 2021-12-28
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多