整数加法不正确,但双精度正常

时间:2019-05-06 21:56:17

标签: c++ templates int double

我知道这不是要问的正确问题,但是对于我的一生,我不知道是什么原因导致了这个问题。

我需要写一个问题,该问题需要使用一定数量的整数或双精度数并返回它们的和。

我已经编写了实现此目的的代码,并确保每次更改内容时都要进行检查。

#include<iostream>
using namespace std;

template <class T>
class totalClass
{
private:
T *p;
T Total;
T sum;
int size;
public:
        T total(int x)
{
    size = x;
    p = new T[x];

    for (int i = 0; i < size; i++)
        p[i] = T();

    if (size > 1)
    {
        for (int i = 0; i < size; ++i)
        {
            cin >> sum;
            Total += sum;
        }
    }
    return Total;
}
};

int main()
{
int size, result1;
double result2;

cout << "Enter: ";
cin >> size;

cout << "the number of ints you wish to enter: Enter: " << size << " integers:";
totalClass<int> test;
result1 = test.total(size);
cout << " Total = " << result1 << endl;

cout << "Enter: ";
cin >> size;

cout << "the number of doubles you wish to enter: Enter: " << size << " doubles:";
totalClass<double> test2;
result2 = test2.total(size);
cout << " Total = " << result2 << endl;
}

我的双打加法正确,但是我的整数加法似乎总是加起来有些疯狂。我的问题有什么看不见的地方吗?

1 个答案:

答案 0 :(得分:0)

如果忘记初始化变量并尝试使用它或对其进行数学运算,则可能会遇到“疯狂的数字”。确保所有变量都已初始化。