How would I rearrange this to get constant variables. I need three of them. I am using this to calculate an average of integers. Are my variables initialized correctly?
#include <iostream>
usingnamespace std;
int main()
{
int n, i;
double num, sum=0.0, average;
cout << "Enter a number of values from 2 to 10: ";
cin >> n;
while (n > 10 || n <= 2)
{
cout << "Invalid input!" << endl;
cout << "Enter a number of values from 2 to 10: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num;
sum += num;
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
constint one = 1;
constint two = 2;
constint ten = 10;
int n{0}, i{0};
double num{0.0}, sum{0.0}, average{0};
cout << "Enter a number of values from 2 to 10: ";
cin >> n;
while (n > ten || n <= two)
{
cout << "Invalid input!" << endl;
cout << "Enter a number of values from 2 to 10: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + one << ". Enter number: ";
cin >> num;
sum += num;
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
initialize all variables. You don't have to init n, because you read it in later, for correctness but its better to initialize it anyway for debugging and consistency and best practices reasons. I did a few of them for you. If you don't need the value later, its also best to scope the loop variable to the for loop instead of making it persist longer.
I interpreted this as using symbolic constants in the place of numeric literals in at least three ways. This would make changing the bounds of the problem later less error-prone.
#include <iostream>
usingnamespace std;
int main()
{
// CONSTANTS
constint LO = 2;
constint HI = 10;
constint NUMBERING_OFFSET = 1;
int numVals;
cout << "Enter a number of values from " << LO << " to " << HI << ": ";
cin >> numVals;
while (numVals > HI || numVals <= LO)
{
cout << "Invalid input!" << endl;
cout << "Enter a number of values from " << LO << " to " << HI << ": ";
cin >> numVals;
}
double input, sum = 0.0, average;
for (int i = 0; i < numVals; ++i)
{
cout << i + NUMBERING_OFFSET << ". Enter number: ";
cin >> input;
sum += input;
}
average = sum / numVals;
cout << "Average = " << average;
return 0;
}