Friday, May 21, 2010

I am finding the difference between two integers in C, how do i make sure the output is a positive number?

# include %26lt;stdio.h%26gt;


# include %26lt;stdlib.h%26gt;





int main( void )


{








int num1;


int num2;








printf("Enter the first number: ");


scanf("%d", %26amp;num1);





printf("\nEnter the second number: ");


scanf("%d", %26amp;num2);





int sum= num1 + num2;


int difference= num1 - num2;





printf("\n\nThe sum of num1 and num2 is %d \n\n", sum);





printf("The difference of num1 and num2 is %d \n\n", difference);











system("PAUSE");


return 0;


}





that is the program that i have so far, the difference output has the ability to come up negatively if the num1 is a smaller number than num 2, how would I make sure that the output for difference is always positive?

I am finding the difference between two integers in C, how do i make sure the output is a positive number?
For a short sequence of code:





if(num1 %26lt; num2) difference = num2 - num1;


else difference = num1 - num2;





Or even shorter, you can use C's "?:" operators.





difference = (num1 %26lt; num2) ? num2 - num1 : num1 - num2;
Reply:Why not just use the abs() function. This function converts any number to a positive value.





Hope this helps
Reply:Run a check to make sure that num1 is greater then num2, the para-code for this should be... (not putting the language in case this is for a class)





if (num1 %26gt; num2)


then int difference = num1 - num2





else-if (num1 %26lt; num2)


then int difference = num2 - num1





else //because this has to be when num1 = num2


then int difference = 0





hope this helps!





ps or you can just make sure that difference is made a positive, but this is the most straightforward method to learn how to use conditional statements


No comments:

Post a Comment