ARRAY PROBLEMS

Pages: 12
I'd recommend going back to your textbook and looking at how to write a simple main() function. You've left out something very basic and important.
Yueeng wrote:
Do you mean that the change happens on volts[j] will be lost when leave the function?
The change happens on the array in main, which is why there is no reason to return a pointer to an array you already have.

When you pass an array, you are actually passing a pointer to it by value, thus the array is accessed by reference and not copied.
Last edited on
1
2
double num [i]={10.62, 7.23, 15.17, 20.15, 9.62};
double num [j]={8.51, 6.58, 7.35, 15.12, 2.05};




Your instructions told you to define 3 arrays, one of which is current, one of which is resistance, and one of which is voltage. You tried to define two arrays, both named num.

Change the words num in the above arrays to current and resistance, and change i and j to 5.

For instance,
double current[5] = {10.62, 7.23, 15.17, 20.15, 9.62};

CURRENT and RESISTANCE are already OK, but the VOLTS is still in error... can somebody check it please... thanks.!

#include<iostream.h>
#include<conio.h>
double calcVolts(double current[5],double resistance[5],double volts[5]);
main()
{
int x;
double current[5]={10.62,7.23,15.12,20.15,9.62};
double resistance[5]={8.51,6.58,7.35,15.12,2.05};
double volts[5];
for(x=0;x<5;x++)
{
volts[x]=calcVolts(current,resistance,volts);
}
cout<<"Current \t\t Resistance \t\t Volts"<<endl<<endl;
for(x=0;x<5;x++)
{
cout<<"current["<<x<<"]: "<<current[x] <<" \t resistance["<<x<<"]: "<<resistance[x]<<" \t volts["<<x<<"]: "<<volts[x]<<endl;
}
getch();
}
double calcVolts(double current[5],double resistance[5],double volts[5])
{
int x; double volt[5];
for(x=0;x<5;x++)
{
volt[x]=current[x]*resistance[x];
return volt[x];
}
return 0;
}
Please use code tags when posting
http://www.cplusplus.com/articles/z13hAqkS/

#include<iostream.h> should be #include<iostream>

#include<conio.h> I believe conio.h is deprecated and should not be used at all

as LB has already stated your calcVolts function should not return a value of any kind
double calcVolts(double current[5],double resistance[5],double volts[5]);

it should look like this
void calcVolts(double current[], double resistance[], double volts[], const int SIZE);

you only need to call the calcVolts function once so the first for loop is not needed
1
2
3
4
for(x=0;x<5;x++)
 {
 volts[x]=calcVolts(current,resistance,volts);
 }



you don't wan't to define a local array in your calcVolts function
int x; double volt[5];

also you wan't to avoid the use of magic numbers so when you create a for loop
it should look something like this

1
2
3
4
const int SIZE = 5;

for(int i = 0; i < SIZE; i++)
//do something 
Last edited on
Topic archived. No new replies allowed.
Pages: 12