The task: to find the arithmetic mean of 10 random numbers ranging from 1 to 40. The problem is that they do not want to compile after adding this line here sum += r; .

 #include "pch.h" #include <iostream> #include <iomanip> using namespace std; int main() { int i, r, sum; srand(time(NULL)); for (i = 1; i <= 10; i++) { r = 1 + rand() % (40 - 1); sum += r; cout << r << endl; } cout << "Average" << sum/10; } 
  • It is necessary to initialize the variables. int i = 0, r = 0, sum = 0; - andy.37

2 answers 2

Compiled - but with a warning about the use of the uninitialized variable sum .

Judge for yourself - you declared sum without initialization. Those. there is some rubbish in it. After that, add the value of r to the garbage - and what's the point in it, if you do not know what you add it to, actually? ..

  • Yes indeed. Thank you;) - whyred_
  • Yes, I just translated a compiler message for you that you didn’t pay attention to ... - Harry

To begin with: what are you doing in this line? You add to the number ... which is not clear for what, since you have not initialized it. And continue to bring your "error".

In general, the analysis of the code:

 #include "pch.h"//зачем? #include <iostream> #include <iomanip>//зачем? using namespace std;// плохая вещь, если используете, то лучше локально int main() { int i, r, sum;// инициализация где? srand(time(NULL)); for (i = 1; i <= 10; i++) {// в с принято вести отсчет от 0, i++ может быть медленнее чем ++i r = 1 + rand() % (40 - 1); sum += r; cout << r << endl; } cout << "Average" << sum/10;// у вас получится целое число, что, я думаю, сдесь не уместно, лучше использовать sum/10.f - так вы получите дробное число. }//где return?