【问题标题】:average of array error (worked with int)数组误差的平均值(与 int 一起使用)
【发布时间】:2014-12-02 12:22:37
【问题描述】:

在这里开始感到沮丧。自我认为这里是菜鸟。我正在关注 John Deitel 的“java 如何编程”一书,以及我的一个朋友(前 CS 学生)发给我的一些非常随机的文档。 我编写了代码来计算 ints 的平均值,效果很好。 然后我想在doubles 中对其进行测试,但仍然出现错误,即使当我按下 ctrl+1 时“工具已成功完成”。我后来发现其他人的代码执行相同的任务,我有点理解,但我想知道我的代码有什么问题。

我也尝试将 racecounter 设置为 double 以删除 average = (double) total / raceCounter;,这导致了更多错误。

import java.util.Scanner;

public class RaceAvgNoNamesDouble
{
   public static void main( String[] args)
   {
      Scanner input = new Scanner( System.in );

      double total;
      int raceCounter;
      double racetime;
      double average;

      total = 0;
      raceCounter = 0;

      System.out.print( "Enter race time or -1 calculate: ");
      racetime = input.nextDouble();

      while (racetime != -1)
      {
        total = total + racetime;
        raceCounter = raceCounter + 1;
        System.out.print( "Enter race time or -1 calculate: ");
        racetime = input.nextDouble();
      }

      if ( raceCounter != 0)
      {
        average = (double) total / raceCounter;
        System.out.printf( "\nTotal of the %d races entered %d\n", raceCounter, total );
        System.out.printf( "Race average is %.2f\n", average);
      }
      else
         System.out.println( "No races were entered");
    }
  }

【问题讨论】:

  • 如果你把raceCounter的类型改成double会发生什么?
  • “但不断出现错误”/“更多错误”:什么错误?
  • 同样的错误,好像它没有被分配为双重,现在把截图放到主帖中

标签: java arrays time runtime-error average


【解决方案1】:

看来您在第一个 printf 语句中犯了一个小错误。由于total 是双精度,因此您应该使用%f 格式而不是%d 格式。

【讨论】:

  • 完美!!!!!!!!!!!!!!!我不敢相信事情就这么简单。我编写的 90% 的代码都来自在线/书籍/论坛,有些部分我错过了逻辑。你救了我一个鼠标和显示器,因为他们正在从我的顶层去一楼的路上:D
  • 不客气,请考虑接受此答案,如果它有助于解决您的问题,则可以关闭该问题。
【解决方案2】:

你不能使用printf 格式%d 作为双精度,这是问题所在,使用%f,像这样:

System.out.printf( "\nTotal of the %d races entered %.2f\n", raceCounter, total );

欲了解更多信息,请参阅this tutorial


还要注意average = (double) total / raceCounter; 中的演员表是多余的

【讨论】:

    【解决方案3】:

    我没有看到任何逻辑错误,除了您的打印方式可能无法正常工作,因为总计是“双倍”。您需要将其更改为 -

    System.out.printf("\n输入的 %d 种族总数 %.2f\n", 比赛计数器,总数);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多