简体   繁体   中英

Why am i getting exremely large numbers when adding elements of an array in c++?

I was trying to add the first 4 numbers of my array. When I test it I always get the number "4201077" even though the first numbers 4 numbers are 1 2 3 and 4. When I try with different numbers starting, I get a slightly different variation such as "4201092". What am I doing wrong? code:

int main(){
   int a [10];
   int count;


   for (int i = 0; i < 10; i ++)
       cin >> a[i];

   int i = 0;
      while ( i < 4){
       count += a[i];
       i++;
      }

   cout << count;
    
}

You never initialize count to hold any value. The line count += a[i]; reads from count in order to add a[i] to that value. In C++, reading from an uninitialized variable is undefined behavior in most cases, including this one. Therefore, your program might do anything at all, including (but not limited to) printing the wrong result, crashing, or doing nothing at all.

// You have:
int count;

// Replace with:
int count = 0;

Always turn on all compiler warnings, and fix any that appear. Every compiler in common use will flag the line count += a[i]; with a warning for reading from an uninitialized variable. For example, gcc says this:

main.cpp: In function 'int main()':
main.cpp:14:14: warning: 'count' is used uninitialized in this function [-Wuninitialized]
   14 |        count += a[i];
      |        ~~~~~~^~~~~~~

Reading uninitialized variables is UB: https://en.cppreference.com/w/cpp/language/ub - which you do with count += a[i]; when you have never initialized count .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM