Back to Problem Solutions forum
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.
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
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);