草庐IT

c++ - 来自类方法的家庭作业 : Cout incorrectly handling a return value of 0. 0

coder 2024-02-21 原文

首先,这是作业,所以我不能为任意大小的数组动态分配内存,也不能使用 vector .

我有一个包含 double 的类包含 30 个元素的数组,以及两个其他变量,用于跟踪已添加的元素数量和可存储的最大元素数量。

有几种方法可以返回数组中元素的最高值、最低值、平均值和总计。其中一种方法的示例是...

double Stats::sum() const
{
  double sum = 0.0;

  for (unsigned short i = 0; i < nElements; ++i)
    sum += stats[i];

  return sum;
};

在我的 main()函数我有一个 cout声明...

cout << "\nTotal rainfall for " << MonthlyRainfall.size() << " months is "
     << MonthlyRainfall.sum() << " inches.\n";

当数组中有值时,输出就是我所期望的...

Total rainfall for 1 months is 1.5 inches.

但是,当数组中没有值时(该方法返回 0.0),但输出看起来像...

Total rainfall for 0 months is -1.$ inches.

任何人都可以帮助我了解 cout 中发生的事情吗?导致我的方法返回的 0.0 按原样输出的语句?

注意:在main()函数的开始处,执行了如下语句来格式化十进制输出。 cout << fixed << showpoint << setprecision(1);


Update I guess it was late and I was calling the average() method instead of sum(). I have fixed it and you also pointed out that I needed to make a couple changes to the average method to ensure a divide by 0 is not happening. (=


最佳答案

被零除明确定义为正无穷大或负无穷大。默认显示为

Inf

-Inf

(至少在我的机器上)。

setprecison 搞砸了,see this other question .

关于c++ - 来自类方法的家庭作业 : Cout incorrectly handling a return value of 0. 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671300/

有关c++ - 来自类方法的家庭作业 : Cout incorrectly handling a return value of 0. 0的更多相关文章

随机推荐