Search code examples
ctype-conversion

Why do my integer and float value disappear when compiling and running my code?


The aim of my code is to take a users height in cm and convert is to feet and inches in the form f'i. when running the code, it results in anything using the feet and inches variables giving 0. I have a feeling the solution is really simple and I just can't see it. btw I am new to coding so keep that in mind please (I won't understand technical stuff).

I tried some of the solutions people gave online, most notably using %, to get the remainder of dividing something, however changing the variable type to int messes stuff up and results in a height of several thousand feet, despite a height in cm of 190. here is the code:

/*cent_to_feet.c -- converts a user's height in centimetres to feet and inches*/
#include <stdio.h>
#include <math.h>
int main(void)
{
    float centimetres;// feet are inches/12, take the leftover and thats the inches
    int inches = centimetres/3;
    float leftoverinches = inches%12;
    printf("What is your height in centimetres?\n");
    printf("Enter here:_____\b\b\b\b\b");//user enters height in cm
    scanf("%f", &centimetres);//takes user data and denotes it 'cm'
    if (centimetres < 180){
    printf("Below 180 centimeters ");
    }
    else {
    printf("Wow thats pretty tall!\n That's %.0f feet and %.0f inches", centimetres/30.48, leftoverinches);
    } 
    printf("\nIn any case, you're %.0f'%d", centimetres/30.48, leftoverinches);
    getchar();
    getchar();

    return 0;
}

Solution

  • C code is executed from the top to the bottom, like when reading a book. Simplified, each statement is executed at the point when it is "read" by the processor. All values of the variables involved are used at that point in time.

    So when you execute inches = centimetres/3;, the centimetres has not yet been initialized and therefore contains "garbage". That you write to centimetres later on in the scanf statement doesn't matter, the code doing the calculation has already executed. The program won't somehow magically rewind and execute the code again.

    Expressions in C signify calculations, not relations. inches = centimetres/3 does not mean that the variable inches is always centimetres/3. Rather it means "divide the value of centimetres by 3 then store the result in inches".

    The majority of all other programming languages behaves the same.