I'm working on a program and this is my first time using arrays. This part of the code is fairly self explanatory. I've been trying to play around with data types for the array because I keep getting weird output values depending on the date type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int i;
double p[i];
for (i=0; i<5; i++)
{
cout<<"Input hours driven: ";
cin>>y;
p[i]=y;
}
for (i=0; i<5; i++)
{
cout<<p[i]<<endl;
}
If I assign it as a double, and input 5 '1', this is my output:
1
1
6.95324e-310
6.95324e-310
1
However if I define it as float, my output is this:
1
1
1
1
4.18829e+32
Float won't hold anything passed 4 values properly.
I can't use int because these eventually will have decimal places.
Why is this happening? How do I go about fixing this?
Line 1: i is an uninitialized variable. It contains garbage.
Line 2: It's not legal C++ to dimension an array with a non-const variable. Some compilers do allow this as a non-standard extension, however, how big do you think the array is if i is garbage?
I see. That makes sense.
The reason I wrote it this way is because 5 is actually supposed to be another variable z which is defined with user input earlier in the code. So in this case, would I just dimension it with a maximum value, say,
double p[20]; ?
Or is there a more correct way to do this sort of thing?