why won't this C++ code work?

GEC: Discuss gaming, computers and electronics and venture into the bizarre world of STGODs.

Moderator: Thanas

Post Reply
User avatar
Jaepheth
Jedi Master
Posts: 1055
Joined: 2004-03-18 02:13am
Location: between epsilon and zero

why won't this C++ code work?

Post by Jaepheth »

I need to take a few integers, put them through a function, and then round UP to the next integer (0.000001 = 1)

I wrote the following test program:

Code: Select all

#include <iostream>
#include <cmath>
#include <fstream>


int main(){
ofstream data;
data.open("test.csv");
int test=0;
	for(int i=10;i>0;i--){
		for(int j=10;j>0;j--){
			test=int(ceil(i/j)+.5);
			data<<i<<","<<j<<","<<test<<endl;
		}
	}
data.close();
}
which I opened in Excel and compared with the decimal values to get:

Code: Select all

i   j  test  decimal
5	5	1	1
5	4	1	1.25
5	3	1	1.666666667
5	2	2	2.5
5	1	5	5
4	5	0	0.8
4	4	1	1
4	3	1	1.333333333
4	2	2	2
4	1	4	4
3	5	0	0.6
3	4	0	0.75
3	3	1	1
3	2	1	1.5
3	1	3	3
2	5	0	0.4
2	4	0	0.5
2	3	0	0.666666667
2	2	1	1
2	1	2	2
1	5	0	0.2
1	4	0	0.25
1	3	0	0.333333333
1	2	0	0.5
1	1	1	1

it seems to be always rounding down?

Does anyone see what I'm doing wrong?
(compiler in use: Cygnus' CygWin g++ 2.91.57)


PS. it's in a rather rather large recursive algorithm, so clock cycles is a concern, which is why I'd rather not use something like:
(x/y%1)==0 ? return x/y : return x/y-(x/y%1);
Children of the Ancients
I'm sorry, but the number you have dialed is imaginary. Please rotate the phone by 90 degrees and try again.
User avatar
Beowulf
The Patrician
Posts: 10621
Joined: 2002-07-04 01:18am
Location: 32ULV

Post by Beowulf »

Because you're using integer arithmetic. The only results of integer arthimetic is integers. The fractional portion is discarded. You'll need to cast one or both of the variables to float or double, then cast the result back to an int.
"preemptive killing of cops might not be such a bad idea from a personal saftey[sic] standpoint..." --Keevan Colton
"There's a word for bias you can't see: Yours." -- William Saletan
User avatar
Pint0 Xtreme
Jedi Council Member
Posts: 2430
Joined: 2004-12-14 01:40am
Location: The City of Angels
Contact:

Post by Pint0 Xtreme »

Any number type casted into an integer will always result in its 'floor' value. Type cast it into an integer after you've determined the ceiling.
Image
User avatar
Jaepheth
Jedi Master
Posts: 1055
Joined: 2004-03-18 02:13am
Location: between epsilon and zero

Post by Jaepheth »

ok, cool. thanks for the advice guys.
Children of the Ancients
I'm sorry, but the number you have dialed is imaginary. Please rotate the phone by 90 degrees and try again.
Post Reply