整数无法正确添加,但双打工作正常

Integers not getting added up correctly but doubles are working fine

本文关键字:打工 工作 添加 整数      更新时间:2023-10-16

我知道这不是要问的正确问题,但是对于我的一生,我无法弄清楚是什么原因引起了这个问题。

我需要编写一个问题,该问题需要一定数量的整数或双打并返回其总和。

我已经编写了代码来制作这项工作,请确保每次更改某些内容时检查。

#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;
}

我的双打正确添加了,但是我的整数添加似乎总是加起来了一些疯狂的数字。我看不到我的问题有问题吗?

如果您忘记初始化变量并尝试使用它或使用数学来进行数学,则可能最终得到"疯狂数字"。确保所有变量都是初始化的。