Home > Back-end >  Int and Float arrays give wrong results after adding numbers using loops
Int and Float arrays give wrong results after adding numbers using loops

Time:06-25

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

CodePudding user response:

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;
}
  • Related