gpt4 book ai didi

Java IO "NaN"问题

转载 作者:行者123 更新时间:2023-12-02 01:13:47 27 4
gpt4 key购买 nike

我有一个名为 Numbers.txt 的文件,其中包含以下内容:

8.5

83.45, 90.2

120.00, 11.05

190.00

我编写了使用文件内容来计算文件中数字的总和和平均值的代码,但是当我运行代码时,平均值结果为“NaN”

代码:

package lab13;

import java.util.Scanner;

import java.io.*;

public class problem1 {

public static void main(String[] args) throws IOException
{

double sum = 0;
int count = 0;
double num,total = 0;
double average = total/count;


File file = new File("Numbers.txt");
Scanner scan = new Scanner(file);


while (scan.hasNext())
{
double number = scan.nextDouble();

sum = sum + number;
}

while (scan.hasNextDouble())
{
num = scan.nextDouble();
System.out.println(num);
count++;
total += num;

}

scan.close();

System.out.println("The sum of the numbers in " +
"Numbers.txt is " + sum );

System.out.println("The average of the numbers in " +
"Numbers.txt is " + average );


}
}

输出:

Numbers.txt 中的数字总和为 503.2

Numbers.txt 中数字的平均值为 NaN

最佳答案

你需要做

double average = total/count;

之后您将获得totalcount的值

但是还要注意

while (scan.hasNext()) 流耗尽时,while (scan.hasNextDouble()) 也将耗尽

这个问题可以克服,但只需循环一次

关于Java IO "NaN"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58967310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com