Hi!
I have a very stupid question, but I don't understand why it doesn't work!
Where did I go wrong? Thank you!Code:int x=360, y=100; fload d; .. d = (x/y); printf("%f\n", d); // d returns 3.00000, but it should 3.60000
Hi!
I have a very stupid question, but I don't understand why it doesn't work!
Where did I go wrong? Thank you!Code:int x=360, y=100; fload d; .. d = (x/y); printf("%f\n", d); // d returns 3.00000, but it should 3.60000
instead of try thisCode:d = (x/y);Code:d = (float)(x/y);
Thanks! That worked!!
Are you shure ?Originally Posted by q6z4k
the result of
is an int. You want it to be a float so you have to either cast x or y to a float.Code:(x/y);
should workCode:d = ((float)x/y);
Kurt
remember
1. int / int ---> int
2. int / float ---> float
3. float / float ---> float
4. double / double ---> double
so u could have dont something like this as well
ssharish2005Code:#include<stdio.h> int main() { int x=360; float y=100.0; printf("%f",x/y); getchar(); return 0; } /*my ouput 3.600000 */
Code:int x; int y; double z = (1.0 * x) / y;
Code:#include <stdio.h> void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){ puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9 /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i] ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][ t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}
When you involve integral types (eg, char, int, long) in division, the result is truncuated: the digits to the right of the decimal place are simply discarded. 3/2 results in 1.
Floating point division (float, double, and long double) saves the decimal part of the number. Due to promotion, if there is a floating point number in an expression, the other values in the expression are converted to floating point numbers too. So you just have to cast one of your numbers to float or double and you'll get the result you want. Alternatively, you can use a number with a decimal point (like 3.0/2), which is automatically a floating point number, or a prefix like F, which makes the literal floating-point.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.