-7

I am new to c, please help, the answer to this is always zero.why? Instead of converting KM to Metres or centimetres(sorry for typos);

#include <stdio.h>

int main()
{
    float Km;
    float metres;
    float inches;
    float centimetres;

    printf("Welcome, please enter the distance in Km.\n");

    scanf("%f", &Km);
    metres = Km * 1000;
    centimetres = Km*100000;
    inches = Km*25/1000000;

    printf("Distance In Metres is:\n");
    printf("%f\n", &metres);

    printf("Distance in Centimeters is:\n");
    printf("%f\n", &centimetres);

    printf("Distance in Inches is:\n");
    printf("%f\n", &inches);

    printf("bye\n");

    return 0;
}
adrian
  • 1,439
  • 1
  • 15
  • 23

2 Answers2

2

printf function writes the value of the variable. The ampersand operator & turns your value into a pointer and that's the error. Instead of printing the actual value of your variables, you are printing the address memory of the pointer.

Read documentation on printf function. More info on & and * here.

1

You are printing the location of the variables. The calculation is fine, but you're not actually printing the value of the variable. You're printing where it is in memory.

The & operator will give the location of the variable. You can fix your program by removing the &s in the printf statements, i.e. this:

printf("%f\n", &inches);

becomes:

printf("%f\n", inches); 

Also, here is a link to a pretty in-depth printf() reference; to learn more about pointers, you can go to this page.

adrian
  • 1,439
  • 1
  • 15
  • 23
  • "If you want to print the location, ..., use a decimal or hexadecimal formatter (%d and %x" is poor advice and detracts from a good answer - recommend delete that paragraph. `%d` is for `int`, not an address. To print a `void *`, use `%p`. – chux - Reinstate Monica Jul 26 '17 at 21:51