Need help with a puzzling outcome.

closed account (oN3AqMoL)
I'm working on a science experiment to see which is faster: Java, or C++.
I've been working on the code for the experiments but in one experiment where I'm seeing which can do the fastest math calculation, they both end up with different answers to the same problem. Here's the code:


Compiler: Codeblocks


C++:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
int main()
{
long addnum;
long counter = 0;
double dvidenum = 1;
long holdernum[3];
holdernum[1] = 1;
holdernum[2] = 1;
holdernum[0] = 1;

while(counter < 10000000)
{


holdernum[0] = holdernum[0] + counter;
holdernum[1] = holdernum[1] - counter;
dvidenum = dvidenum / counter;
holdernum[3] = holdernum[2] * counter;
counter++;

}
addnum = holdernum[0] + holdernum[2] - holdernum[1];
cout<<"testdone";

cout<<addnum;
return 0;
}



Compiler: Eclipse


Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class exp
{
public static void main(String args[])
{
long addnum;
long counter = 0;
double dvidenum = 1;
long holdernum[]=new long[3];
holdernum[1] = 1;
holdernum[2] = 1;
holdernum[0] = 1;

while(counter < 10000000)
{


holdernum[0] = holdernum[0] + counter;
holdernum[1] = holdernum[1] - counter;
holdernum[2] = holdernum[2] * counter;
dvidenum= dvidenum / counter;
counter = counter + 1;
}
addnum = holdernum[0] + holdernum[2] - holdernum[1];

System.out.println("testdone\n");
System.out.println(addnum);

}
}


Here's the answer to the one in C++:
266447233
And here's the one in java:
99999990000000
Please help!
Last edited on
If you step through with the debugger you will see the java result is correct. The c++ version's result is overrunning. Change addnum and holdernum to long long. You also have a typo on line 19 on the c++ version, holdernum[3].
I am also surprised they dont throw division by zero errors.
Last edited on
closed account (oN3AqMoL)
Thanks! That did it!
Topic archived. No new replies allowed.