• C

How do I use the mudulus operator in printf in C programming?

I'm getting the compiler error in Xcode: "Invalid operands to binary expression". How do I use the modulus in this simple height conversion program?

#include <stdio.h>

int main(int argc, const char * argv[]) {

    int centimeterHeight;
    
    printf("Enter height in centimeters: ");
    scanf("%d",&centimeterHeight);
    printf("\nYour height is %d feet %d inches",centimeterHeight/2.54/12,(centimeterHeight/2.54)%12);
    
    return 0;
}

Open in new window

shampouyaAsked:
Who is Participating?
 
chaauCommented:
This line will:
inches = (int)(centimeterHeight/2.54)%12;

Open in new window

0
 
phoffricCommented:
When you divided the int by 2.54, the result needs to be converted back to an int.
0
 
shampouyaAuthor Commented:
I got the program to work using a workaround, but the casting to int did not work. I got the same error. Why wouldn't line 12, which I commented out, work?

#include <stdio.h>

int main(int argc, const char * argv[]) {

    int centimeterHeight;
    int feet;
    int inches;
    
    printf("Enter height in centimeters: ");
    scanf("%d",&centimeterHeight);
    feet = centimeterHeight/2.54/12;
    //inches = (int)floor(centimeterHeight/2.54%12);
    inches = (centimeterHeight - 12 * feet * 2.54)/2.54;
    printf("\nYour height is %d feet %d inches\n",feet,inches);
    return 0;
}

Open in new window

0
 
chaauCommented:
With the inches you need to subtract the remaining height after you converted to feet and then divide by 2.54:
(centimeterHeight - centimeterHeight/2.54/12)/2.54

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.