LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

ceil() returns wrong value

Hi!

If I run this simple program in CVI 6.0, all answers are 1.
The first two outputs should be 2, right? What's wrong with
the ceil() function?

Pleas help. Thanks!

Daniel


----------------------------------------------------------

#include
main()
{
int k1, k2, k3, k4;
double m;

k1=ceil(901/900); // ceil() function is wrong!!!
m=ceil(980/900);
k2=ceil(900/900);
k3=floor(901/900);
k4=floor(980/900);


printf("%d, %f, %d, %d, %d", k1, m, k2, k3, k4);
printf("\n\n");
printf("Press Enter to finish.");
getchar();
}

--------------------------------------------------------------
0 Kudos
Message 1 of 4
(3,986 Views)
Daniel,

The C language has specific rules for deciding on the data type of the *result* of an operation, based on the data type of the operands. With division, if at least one of the operands of the division is a double, then the result will also be a double. But if both operands are integers, then the result will also be an integer. In your example, you use literals as operands for your division. These literals, because of the way that you represented them, are treated as integers. This means that the result of the division will also be an integer, which of course means that the "true" result of the division has to be downcast to 1. And it is this value of 1 that is ultimately being passed to the ceil() function.

This has a very simple fix. You'll find that you just change the data type of one of the lterals you'll get the result you're looking for. For example:

k1=ceil(901.0/900);

or, if you're using variables instead of literals, use an explicit cast:

k1=ceil((double)var1/var2);

Luis
NI
0 Kudos
Message 2 of 4
(3,979 Views)
Seems quite a strange behaviour, but only when there are implicit conversions between units. If you divide two doubles all works well:

a = ceil (901.0 / 900.0) => a = 2.00000000 both in case a is a double or an int
The same result using a = ceil ((double)901 / (double)900)

But when you use two integers, seems as if the result is implicitly cast to an integer before being passed to ceil function, so the wrong result:

a = ceil (901 / 900) => a = 1 again the same in case a is a double or an int
as if the statement executed were: a = ceil ( (int)(901 / 900) )

Infact, ceil (1799 / 900) gives 1 while ceil (1800 / 900) gives 2.

I don't know if this is the right explanation but is seems to explain this behaviour and gives you a practical solution to it.


Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 3 of 4
(3,977 Views)
Thanks a lot for your advise!

It works! That's what matters.

Daniel
0 Kudos
Message 4 of 4
(3,971 Views)