Search code examples
cdoublerounding

Turn 0.5 to 1 instead of 0


My cyclomatic complexity in this C program is supposed to be 1, so I can't write if else statements.

#include <stdio.h>
int main()
{ 
    int U,V;
    scanf("%d %d",&U,&V);
    printf("%0d",(U*V)/2);
}

Solution

  • The expression (U*V)/2 performs integer division since all operands are integers. This truncates any fractional part.

    If you want to round up, you first need to perform floating point division, which you can do by changing one operand to a floating point type. Then you can pass the result to the round function which rounds to the nearest integer, with the .5 case being rounded up.

    printf("%0d",(int)round((U*V)/2.0));