INT和Float数组在使用循环添加数字后给出错误的结果

发布于 2025-02-10 06:14:17 字数 782 浏览 2 评论 0原文

对C ++进行一些简单的练习,我卡住了... 当我的总和[t]阵列被声明为整数或浮动时,有时会在最后输出一些疯狂的值,例如4239023或-3.17802e+30(尽管我只添加了范围< -100; 300&gt的少量数字;)。当我将其更改为双倍时,它可以正常工作。为什么INT和Float在这里不工作?

#include <iostream>
using namespace std;

int main()
{
    int t=0;
    int n=0;
    int x=0;
    cout<<"Amount of sums: ";
    cin>>t;
    int sum[t];

    for (int i=0; i<t; i++)
    {
        cout<<"Sum no. "<<i+1<<". How many numbers you wish to add: ";
        cin>>n;
        for (int j=0; j<n; j++)
        {
            cout<<"Insert number "<<j+1<<" : ";
            cin>>x;
            sum[i]+=x;
        }
    }

    for (int i=0; i<t; i++)
    {
        cout<<sum[i]<<endl;
    }

    return 0;
}

Doing some simple exercies with C++ and I'm stuck...
When my sum[t] array is declared as integer or float it sometimes outputs at the end some crazy values like for example 4239023 or -3.17802e+30 (despite the fact that I add only small numbers from range <-100; 300>). When I change it for double it works correctly. Why int and float don't work here?

#include <iostream>
using namespace std;

int main()
{
    int t=0;
    int n=0;
    int x=0;
    cout<<"Amount of sums: ";
    cin>>t;
    int sum[t];

    for (int i=0; i<t; i++)
    {
        cout<<"Sum no. "<<i+1<<". How many numbers you wish to add: ";
        cin>>n;
        for (int j=0; j<n; j++)
        {
            cout<<"Insert number "<<j+1<<" : ";
            cin>>x;
            sum[i]+=x;
        }
    }

    for (int i=0; i<t; i++)
    {
        cout<<sum[i]<<endl;
    }

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉城已无爱 2025-02-17 06:14:17

收到t的值后,应将其总和数组初始化为零。您可以这样做:

for (int i=0; i<t; i++)
{
    sum[i] = 0;
}

You should initialize your array of sums to zeroes after you receive the value of t. You could do it like this:

for (int i=0; i<t; i++)
{
    sum[i] = 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文