简体   繁体   中英

Adding the contents of a simple array

I am a total newcomer to the world of C++, and not much more experienced in any other languages, so please forgive me for the bad syntax and indentation etc etc...

Can someone please explain to me why this simple program will print the array values that I input, but won't add up the array values?

#include <iostream>

 using namespace std;

int main(){

  int alpha[8];
  int sum=0;

 for(int x=0; x<8; x++){
    cin>>alpha[x];
  }
 for(int x=0; x<8; x++){
    cout<<alpha[x];
  sum += alpha[x];
  return sum;

  }
  cout<<sum;

  return 0;
}

In your 2nd for statement, you have a return . The code reaches the return and exits your program.

You may want to move code to a function to keep the return or remove it.

BTW, you can find this out by using a debugger.

This program will simply print the first value and then it will end up as you put a return statement in the for loop

for(int x=0; x<8; x++){
    cout<<alpha[x];
  sum += alpha[x];
  return sum; /* it will end up here */

  }

remove this statement and you will get all the values printed and the sum also

Thanks for the help, I have modified my code and made it into this: 感谢您的帮助,我已经修改我的代码,并把它做成这样:

#include <iostream>

using namespace std;

int main()
    {
    int alpha[8];
    int sum = 0;

    for (int x = 0; x<8; x++)
    {
        cin >> alpha[x];
    }
    for (int x = 0; x<8; x++)
    {
        cout << alpha[x];
    } 
    for (int x = 0; x<8; x++) 
    {
        sum = sum + alpha[x];
    }
    cout << sum;
    system("PAUSE");
    return 0;
}

having tried your suggestions, I couldn't make it work initially, so I fiddled with the formatting. The program seems to work now. I would assume that there was something wrong with either my formatting post-"return" removal, or there was something procedurally wrong with the Eclipse/MinGW setup I had. I seem to have more success with Visual Studio.

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