Problem number 6 rounding in c language

Back to Problem Solutions forum

ta.shrivastava     2019-10-16 17:24:03

This is first time I am asking for help, so please forgive me if I posted on the wrong section.

Basically, I am trying to add 0.5 if a number is positive, and minus 0.5 if it is negative. but even then, my program is not giving me correct answers.

I have tested it on the given numbers for the testing on the task page. it does work for the 400 / 5, but any other value, (11 / -3, 12 / 8) do not give the correct answer.

Below, is the source code of the program, take a look at it, and tell me what I am doing wrong.

include <stdio.h>

int main(void)

{

int i, n;

long dividend, divisor;

float result;

printf("How many pairs do you wish to divide?");

scanf("%d",&n);

for(i = 0; i < n; i++)

{

printf("Enter the values to divide:");

scanf("%d%d",÷nd,&divisor);

result=dividend/divisor;

if(result>0)//condition to check whether the number is positive or not.

{

result=result+0.5;

}

else

{

result=result-0.5;

}

printf("%d", (int) result);//typecasting result, then printing it.

}

return 0;

}

It should also be noted that when I tried to run the program without the if condition and type casting the result, it still gave me the wrong answer.

Rather than giving me correct answer of 12 / 8 (which is 1.5,) it gave me simply 1.0000

Quandray     2019-10-17 06:37:44
User avatar

If you divide a long by a long, the result will be a long. Try this code

long dividend=12,divisor=8;
float result;
printf("%ld\n",dividend/divisor);  // 1
result=dividend/divisor;           // 1
printf("%f\n",result);
result=(float)dividend/divisor;    // 1.5
printf("%f\n",result);
Please login and solve 5 problems to be able to post at forum