LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 3

Remainder and rounding of real numbers in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Print the remainder of 7.5 / 2 and 3.14 / 2.1, and round 2.5 and −2.5 with round(), floor() and ceil().

Solution
main.c
#include <math.h>
#include <stdio.h>

int main(void) {
    printf("%.2f %.2f\n", fmod(7.5, 2), fmod(3.14, 2.1));
    double v[] = {2.5, -2.5};
    for (int i = 0; i < 2; i++)
        printf("%4.1f: round %4.1f floor %4.1f ceil %4.1f\n", v[i], round(v[i]), floor(v[i]), ceil(v[i]));
    return 0;
}

Output Verified by compiling and running

1.50 1.04
 2.5: round  3.0 floor  2.0 ceil  3.0
-2.5: round -3.0 floor -3.0 ceil -2.0

fmod() is the floating-point remainder. round() rounds halves away from zero, floor() toward −∞ and ceil() toward +∞ – so the negative half rounds differently from what many expect.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links