float array into function

Feb 21, 2013 at 7:45pm
so i made this with int which works properly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int blue(int array[], int num);

int main (){
    int red [3]={2,9,8};
    cout << "the sum of the numbers in the array is: " << blue(red,3) << endl;
    system("pause");
    return 0;
}

int blue(int array[], int num){
    int sum=0;
    for(int x=0;x<num;x++){
            sum+=array[x];
            }
    return sum;
}


then i wanted to make one with decimals so i used float but i can't manage to make it work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

float blue(float array[],int num);

int main (){
    float red [3]={2.5,9.6,8.7};
    cout << "the sum of the numbers in the array is: " << blue(red,3) << endl;
    system("pause");
    return 0;
}

float blue(float array[],int num){
      float sum=0;
      for(float x=0;x<num;x++){
                sum+=array[x];
                }
      return sum;
      }
Feb 21, 2013 at 7:49pm
x should still be an int.
Feb 21, 2013 at 7:53pm
EDIT: (thanks to Peter87)
1
2
3
4
5
6
float blue(float array[],int num){
      float sum=0;
      for(int x=0;x<num;x++) //To access element to array you need integer!
                sum+=array[x];
      return sum;
}

Last edited on Feb 21, 2013 at 8:03pm
Feb 21, 2013 at 7:55pm
eraggo wrote:
For loops use int
for loops can use any types. The problem is that you can't use floating point numbers as an index to an array. It has to be an integer.
Feb 21, 2013 at 7:58pm
CRAP :D i knew something i said was wrong.
^agreed. Pass on
Feb 21, 2013 at 8:00pm
Sorry, it's just me being pedantic. If you think I'm a jackass, please say so.
Feb 21, 2013 at 8:01pm
Fixed "the fix". Thanks for reminder
Feb 22, 2013 at 4:25am
thanks
Topic archived. No new replies allowed.