• 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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

phoffric\Commented:
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
chaauCommented:
This line will:
inches = (int)(centimeterHeight/2.54)%12;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.