Page 1 of 1

why won't this C++ code work?

Posted: 2006-10-17 11:52pm
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);

Posted: 2006-10-18 12:11am
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.

Posted: 2006-10-18 12:22am
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.

Posted: 2006-10-18 12:24am
by Jaepheth
ok, cool. thanks for the advice guys.