Reputation: 2680
int number1 = 23;
int number2 = 100;
printf("Output: %.2d", double(number1) / number2);
This I want:
Output: 0.23
This I get:
error: expected expression before ‘double’
I don't understand the error message. How to do cast the integer to double and perform the calculation?
Upvotes: 0
Views: 2007
Reputation: 419
Let's have a look at some basics of format specifiers shall we?
**Format specifier** **Characters matched** **Argument type**
%c any single character char
%d, %i integer integer type
%u integer unsigned
%o octal integer unsigned
%x, %X hex integer unsigned
%e, %E,%f, %g, %G floating point
number floating type
%p address format void *
%s any sequence of
non-whitespace
characters char
You used "%d" instead of "%f" there is no way the compiler is gonna print a floating point value.
Upvotes: 1
Reputation: 22813
That's because you are typecasting the wrong way, also the format specifier is incorrect:
printf("Output: %.2f", (double)number1 / number2);
Here is the Output:
Upvotes: 2
Reputation: 612794
You have two errors.
Firstly you are casting incorrectly. Cast to double like this:
(double)number1
Secondly you used the wrong print format specifier. You used d
which is for integers. Use f
instead. Putting it all together gives:
printf("Output: %.2f", (double)number1 / number2);
Upvotes: 1
Reputation: 122373
The correct syntax of cast is (double)number1 / number2
, and you should use %.2f
as the format specifier.
printf("Output: %.2f", (double)number1 / number2);
// ^ ^ ^
Upvotes: 1
Reputation: 10516
Use%f
format specifier
printf("Output: %.2f", (double) number1 / number2);
Upvotes: 1