Reputation: 49
At the momemt, i'm learning the C and the basics of the language, but I have a problem with my code. When I multiply two numbers, I cant get the decimals, even I float the numbers I enter.
My code:
int main()
{
double result_met, km;
result_met = km = 0.0f;
/*Display text*/
printf("Enter values of the distance between the two cities in km's\n");
scanf_s("%d", &km);
/*Formular for a simple km conversion*/
result_met = km * 1000.0f;
/*Result print*/
printf("Meter:%d", result_met);
printf("\nWaiting for a character to be pressed from the keyboard to exit.\n");
getch();
return 0;
}
Upvotes: 0
Views: 132
Reputation: 586
The format specifier for double is %lf
, not %d
You may as well use a float
instead of a double
, it saves memory (which is important when you begin to write big programs), then you must use the format specifier %f
(the "l" in %lf
is for "long", because a double
is a long float
)
When treating decimals, you want to print only a few decimals on the screen (to avoid the printing of a "2.50000001"), then you can use the format specifier %.3f
if you want 3 and only 3 digits printed (3
can be any integer).
for example, the following code :
printf("%.2f\n",3.1415);
has the following output :
3.14
the printf
function has many different format specifier, that can be very useful.
Go see the cpluplus.com reference if you want to learn more about it
Upvotes: 1
Reputation: 22841
The format specifiers are incorrect - it should be %lf
- %d
is for int
.
scanf_s("%lf", &km);
/*Formular for a simple km conversion*/
result_met = km * 1000.0f;
/*Result print*/
printf("Meter:%lf", result_met);
Upvotes: 2