wrote:
> Hi,
> I have this little test program:
> #include <stdio.h>
> int main(){
> float f1 = 2.2;
> double d1 = 3.3;
> int j = f1 * d1;
This is exactly the same as the i2 case below
> int i = (int) f1 * d1;
This is (int) 2.2 * 3.3 ->
2 * 3.3 ->
6.6
assigned to an int as 6
> int i2 = (int) (f1 * d1);
This is (int) (2.2 * 3.3) =>
(int) (7.26) ->
7
> printf("%d, i=%d, j=%d, i2=%d\n", f1*d1, i, j, i2);
^^
This is an error. f1*d1 is a floating point value.
%d is a specifier for signed ints.
Unless a double and an int have exactly the same size,
you have hopelessly munged the arguments to printf.
Unless you are using a C99 compiler, you need to return a
value here, e.g.
return 0;
> }
> I use gcc on Linux to compile it, there is no warning and the result
> is like this:
> 2066953011, i=1075644989, j=6, i2=7
After you change the erroneous "%d" to "%g", the output should look like:
7.26, i=6, j=7, i2=7
> I have several questions:
> 1. Why there is no warning in compiler when I assign the
> multiplication of float and double to integer?
Because there is absolutely nothing wrong with doing so, and there is
nothing to warn about.
> 2. As for the result, I can understand how i2 comes from, but others
> do not make sense to me.
No, you can't understand "how i2 comes from", because the erroneous "%d"
makes a complete hash of your output line.
> Could you give me some pointer?
Don't feed us straight lines.