0

Is there any way to round systemGuess up. In this case the outcome of systemGuess is 5.5 I want it to be 6 how do I do this?

See code below:

 int main(void){

    int systemGuess = 0;
    stystemGuess = (10 - 1)/2 + 1;
    printf(" %d ", stystemmGuess);
}
kamito dono
  • 47
  • 1
  • 7
  • If you want to round normally, add `.5` to the total before assigning to stystemGuess. – Riley Oct 04 '16 at 14:27
  • 1
    It depends on the rounding rules you are trying to apply. Do you want to round all results of integer division up, or round to the nearest integer with a tie-break rule for .5, or what? – Ian Abbott Oct 04 '16 at 14:53

5 Answers5

2

Use floating point division and ceil:

stystemGuess = ceil((10 - 1)/2.0) + 1;

If you want to round 0.4 down, use round instead.

orlp
  • 112,504
  • 36
  • 218
  • 315
1

OP wants to perform an integer division with the result rounded-up.

// If the quotient fraction > 0, return next larger number.
unsigned udiv_ceiling(unsigned n, unsigned d) {
  return (n + d - 1)/d;
}

// If the quotient fraction >= 0.5, return next larger number.
unsigned udiv_nearest_ties_up(unsigned n, unsigned d) {
  return (n + d/2)/d;
}

stystemGuess = udiv_ceiling(10 - 1, 2) + 1;
// or
stystemGuess = udiv_nearest_ties_up(10 - 1, 2) + 1;

Additional code needed to handle negative numbers and in corner cases, protect against n + d - 1 overflow.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

You can use

systemGuess = (10 - 1)/2.0 + 1 + 0.5;

The problem is that you do integer calculation. So e.g. 9/2 is 4. If you use 9/2.0 you have floating point division, which gives you 4.5. Adding 0.5 in the end gives you 6.0 instead of 5.5, so when storing it in systemGuess, you get 6 instead of 5.

jfschaefer
  • 54
  • 2
  • 3
0

Integer division in C truncates toward 0, so if you do the math on the other side of 0 (i.e., on negative numbers), it will "round up". You might do this by subtracting an amount from the dividend and adding half that amount back to the result:

int main(void)
{
    int systemGuess = 0;
    //systemGuess = (10 - 1)/2 + 1;
    systemGuess = (10 - 1 - 20)/2 + 1 + 10;
    printf(" %d ", systemGuess);
}

Probably in your real program there is a more elegant way to make this happen.

Community
  • 1
  • 1
trent
  • 25,033
  • 7
  • 51
  • 90
0

Here you go:

#include <stdio.h>
#include <stdlib.h>

int divide(int x, int y);

int main(void){

    int systemGuess = 0;

    int x = 10-1;
    int y = 2; 

    systemGuess = divide(x,y) + 1;

    printf(" %d ", systemGuess);

}

int divide(int x, int y) {
   int a = (x -1)/y +1;
   return a;
}
John Livingston
  • 43
  • 1
  • 11