John Smith
John Smith

Reputation: 9

Receiving 0.0 when multiplying two doubles in an array

I'm having quite a bit of trouble multiplying two doubles in an array. The result always seems to be 0.0 no matter what I do. I've tried casting, changing the variables from double to int, etc. What am I doing wrong? Having a hard time finding a duplicate question but I'm more than sure there is one. Could someone direct me to it?

My code:

double[] speedK = {100.0, 80.0, 90.0, 110.0, 100.0};
double[] speedMPH = new double[speedK.length];
int n=0;
for(double speedTemp : speedK)
{
    speedMPH[n]= (double)speedTemp * 1.15078;
}
System.out.println(speedMPH[0]);

When I try to print any value of speedMPH the output is 0.0

Upvotes: 0

Views: 104

Answers (3)

August
August

Reputation: 12558

You're only modifying the first element of speedMPH (n is always 0). I'd recommend using a normal for-loop, because you need the current index.

for (int i = 0; i < speedK.length; i++) {
    speedMPH[i] = speedK[i] * 1.15078;
}

Casting to double is not necessary. If you really want to use an enhanced for-loop, you need to increment n:

int n = 0;
for(double speedTemp : speedK) {
    speedMPH[n] = speedTemp * 1.15078;
    n++;
}

Upvotes: 1

Olindholm
Olindholm

Reputation: 390

I'm not neccesarily sure why you're experiencing this issue. Just by looking at it, I can see that all should return 0.0, except the first index or, so called index No. 0.

You're using n as the iterator but you never increase it, thus all inputs you do to the speedMPH array will go into index 0. Here's my code, and it's working just fine.

double[] speedK = {100.0, 80.0, 90.0, 110.0, 100.0};
double[] speedMPH = new double[speedK.length];

for (int i = 0; i < speedK.length; i++) {
    double speedTemp = speedK[i];
    speedMPH[i] = speedTemp * 1.15078;
}

for (int i = 0; i < speedMPH.length; i++) {
    System.out.println(speedMPH[i]);
}

Printing:

115.07799999999999
92.0624
103.57019999999999
126.58579999999999
115.07799999999999

Upvotes: 0

ThatDandyMan
ThatDandyMan

Reputation: 5

The value of n is never increasing. The program continuously changes the value of speedMPH[0], not other values of the array.

Try adding a n++; to your loop.

Upvotes: 0

Related Questions