0

Trying to learn C language, completed upto basic Data types from W3 Schools. So, the question is to input the distance between two cities in km and the output should be in meters, feet, inch, cm. I tried running this code in Vs code. It was showing only "running" in the output box.

#include <stdio.h>
int main(){
    float dist_km,m,cm,feet,inch;
    printf("Enter distance bet two cities in km= ");
    scanf("%f", dist_km);

    m=dist_km*1000;
    cm=m*100;
    inch=cm/2.54;
    feet=inch/12;
    printf("\n dist in m= %f",m);
    printf("\n dist in cm= %f",cm);
    printf("\n dist in inch= %f",inch);
    printf("\n dist in feet= %f",feet);
    return 0;
}

This is the code. The expected should be in meters, cm,etc but I am getting this:

Enter distance bet two cities in km= 29.5
dist in m= 0.000000
 dist in cm= 0.000000
 dist in inch= 0.000000
 dist in feet= 0.000000

Please help me to solve this problem . Thanks

Akash
  • 1
  • 1
  • 1
    Did you get any warnings? – Harith May 20 '23 at 12:35
  • 1
    You must have noticed that you aren't reading the distance correctly, i.e. `dist_km`. Your compiler should have warned about this. So of course, everything it prints is going to be garbage. Hint: `scanf` never takes a `float` as an argument. But it can take a `float *`. Try printing `dist_km`, and forget about the rest of the code until you get that working. – Tom Karzes May 20 '23 at 12:35
  • Voting to close since this problem is essentially just a typo. – Tom Karzes May 20 '23 at 12:36
  • And while you're at it, check the return value of `scanf()` too. – Harith May 20 '23 at 12:36
  • If the compiler doesn't already complain about your code, then you need to enable more warnings. If you build with GCC or Clang then I suggest at least to build with `-Wall -Wextra -Werror`. The first two options enable more warnings, the last one turns all warnings into actual errors. – Some programmer dude May 20 '23 at 12:39
  • Does this answer your question? [How does the scanf function work in C?](https://stackoverflow.com/questions/2062648/how-does-the-scanf-function-work-in-c) – Abderrahmene Rayene Mihoub May 20 '23 at 12:40

2 Answers2

0

Second parameter in scan_f needs to be a pointer the variable being set.

Change the first lines of your code to:

float dist_km,m,cm,feet,inch = 0.0f;
printf("Enter distance bet two cities in km= ");
scanf("%f", &dist_km);

and the code will work as expected:

Enter distance bet two cities in km= 10
dist in m= 10000.000000
 dist in cm= 1000000.000000
 dist in inch= 393700.781250
 dist in feet= 32808.398438
ChrisBD
  • 9,104
  • 3
  • 22
  • 35
0

The problem with your code is that you are passing second parameter of scanf a (float):

scanf("%f", dist_km);

instead you should be passing second argument as (float *), so just change the above line to this:

scanf("%f", &dist_km);

This should help.