0

this is my first question here :)

I want a program that converts lighyears into kms. I defined a constant value for LIGHTYEARSINKM, but even if I just want to convert one lightyear in km, the compiler gives me a different value from the defined one.

For example if give the input 1, the output is 9460500135936.000000 (different from 9460500000000.000000)

What am i doing wrong?

Heres the code I wrote:

#include <stdio.h>
#define LIGHTYEARSINKM 9460500000000.000000

int main( void )
{
float lightyear;
float kilometer;

printf("Lightyears you want to convert into km:\n");
scanf("%f", &lightyear);

kilometer= lightyear * LIGHTYEARSINKM;

printf("%f lightyears are %f kilometer",lightyear,kilometer);

getchar(); 
return 0;
}
Darius E.
  • 13
  • 5
  • Please see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) Also, work with `double` unless you have a *very good* reason not to (an example in an old textbook is not a good reason). You'll only get the first 6 or 7 decimal digits from `float`. With `double` it is roughly 16. – Weather Vane Jun 13 '20 at 15:17
  • @WeatherVane Thanks for your Answer! – Darius E. Jun 17 '20 at 20:08

0 Answers0