使用int进行浮点除法c ++

时间:2018-10-22 02:29:45

标签: c++ arrays

我是C ++的新手,我一直在弄弄到目前为止所学的东西。我搞砸了数组,并想出了以下代码

#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;
}

第40行出现错误:error: expected ';' before numeric constant 我相信这是因为我试图将.0进行浮点除法添加到变量名,我可以使用array_size进行浮点除法的任何方式吗?

2 个答案:

答案 0 :(得分:1)

不能在变量名后附加“ .0”。要将其强制转换为浮动,请使用强制转换语法:

average = float(average + arr[i]) / float(array_size);

请务必提前转换,以免将结果舍入为int:

average = float(average + arr[i] / array_size); // might not work as expected

有关类型转换的更多信息:http://www.cplusplus.com/doc/tutorial/typecasting/

顺便说一句,如果要在平均值上加上数字,则可能要使用其他公式: https://math.stackexchange.com/a/957376

答案 1 :(得分:0)

只需执行操作-每当您对float变量进行算术运算时,操作数将自动转换为double进行操作。所以您只需要:

for(int i = 0; i < array_size - 1; ++i)
    average = (average + arr[i])/array_size;

由于average的类型为float,因此它和arr[i]都将被转换为double以进行(双精度)浮点加法。然后,由于该结果为double,因此array_size也将转换为double并进行浮点除法。最后,该double结果将转换回float并存储在average