In: Computer Science
Write a C program that takes a double value and rounds it up or off using ternary expression in the program. Example, if -2.5 is inputted the value should give -3.0
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments(read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation
please refer code Images
Typed Code:
/*header files*/
#include <stdio.h>
int main()
{
//initializing double datatype variables
double x,rem,y;
printf("Enter value: ");
//getting input from the user
scanf("%lf",&x);
//storing decimal value to rem
//rem = x - (int)x
//let us assume x = 4.5 ==> 4.5 - (int) 4.5 ==> 4.5 - 4 =
0.5
rem = x - (int)x;
//for positive numbers
//if x >= 0 then condition is true
// rem < 0.5 then y = int(x)
// otherwise y = int(x)+1
//for negative numbers
//if x < 0 then condition is false
// rem > -0.5 then y = int(x)
// otherwise y = int(x)-1
y = (x>=0)?(rem<0.5)?((int)x):((int)x +
1):(rem>-0.5)?((int)x):((int)x - 1);
//printing y
printf("Rounded value: %.1lf",y);
return 0;
}
//code ended here
Program using if else to check positive or negative number and round it up or off:
/*header files*/
#include <stdio.h>
int main()
{
//initializing double datatype variables
double x,rem,y;
printf("Enter value: ");
//getting input from the user
scanf("%lf",&x);
//storing decimal value to rem
//rem = x - (int)x
//let us assume x = 4.5 ==> 4.5 - (int) 4.5 ==> 4.5 - 4 =
0.5
rem = x - (int)x;
//for positive numbers
//if x >= 0 then
if(x>=0)
{
// if rem < 0.5 then y = int(x)
// otherwise y = int(x)+1
y = (rem<0.5)?((int)x):((int)x + 1);
}
//for negative numbers
//if x < 0 then
else
{
// if rem > -0.5 then y = int(x)
// otherwise y = int(x)-1
y = (rem>-0.5)?((int)x):((int)x - 1);
}
//printing y
printf("Rounded value: %.1lf",y);
return 0;
}
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!