i'm new with c++, and i was messing around with the stuff i have learned thus far. I was messing with arrays and i came up with the following code
#include <iostream>
using namespace std;
int main()
{
// initializes an array with user defined size
int array_size;
cout << "Enter the amount of number you wish to enter: ";
cin >> array_size;
int arr[array_size];
int i = 0;
int element = 0;
int sum = 0;
float average = 0;
// populates the array with user inputted elements
do
{
cout << "Enter number " << i + 1 << ": ";
cin >> element;
arr[i] = element;
sum = sum + element;
++i;
}
while(i < array_size);
int MAX = arr[0];
for(int i = 1; i < array_size; ++i)
if(arr[i] > MAX)
MAX = arr[i];
int MIN = arr[0];
for(int i = 1; i < array_size; ++i)
if(arr[i] < MIN)
MIN = arr[i];
for(int i = 0; i < array_size - 1; ++i)
average = (average + arr[i])/array_size.0;
cout << "The biggest number that was entered was: " << MAX << endl;
cout << "The smallest number that was entered was: " << MIN << endl;
cout << "The sum of the numbers entered is: " << sum << endl;
cout << "The average of the numbers entered is: " << average << endl;
return 0;
}
i get an error on line 40: error: expected ';' before numeric constant
error: expected ';' before numeric constant
i believe its because im trying to append a .0
for float division to a variable name, any way i can use array_size
to perform float division?
You can not append ".0" to a variable name. To cast it to float, use casting syntax:
average = float(average + arr[i]) / float(array_size);
Be sure to cast early, so that you would not round the result as int:
average = float(average + arr[i] / array_size); // might not work as expected
More on type casting: http://www.cplusplus.com/doc/tutorial/typecasting/
As an aside, if you want to add a number to an average, you might want to use a different formula: https://math.stackexchange.com/a/957376
Just do the operation -- whenever you do arithmatic with float
variables, the operands will automatcially be converted to double
to do the operation. So you just need:
for(int i = 0; i < array_size - 1; ++i)
average = (average + arr[i])/array_size;
since average
has the type float
, it and arr[i]
will be both be converted to double to do a (double precision) floating-point addition. Then, since that result is double
, array_size
will also be converted to double
and a floating point divide will be done. Finally, that double
result will be converted back to float
and stored in average
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.