Use the conditional statement to solve the problem.
Let's consider another solution. Write the condition as follows:
or
For example, if
is positive, then y = 1 - 0 = 1;
x = 0, then y = 0 - 0 = 0;
is negative, then y = 0 - 1 = -1;
Algorithm realization
Read the input value of .
scanf("%d", &x);Compute the value of the sgn function.
if (x > 0) y = 1; else
if (x == 0) y = 0; else
y = -1;Print the answer.
printf("%d\n", y);Algorithm realization — without if
Read the input value of .
scanf("%d", &x);Compute the value of the sgn function.
y = (x > 0) - (x < 0);Print the answer.
printf("%d\n", y);Java realization
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int y, x = con.nextInt();
if (x > 0) y = 1; else
if (x == 0) y = 0; else
y = -1;
System.out.println(y);
con.close();
}
}Python realization
Read the input value of .
x = int(input())Compute the value of the sgn function.
if x > 0: y = 1
elif x == 0: y = 0
else: y = -1Print the answer.
print(y)Python realization — without if
Read the input value of .
x = int(input())Compute the value of the sgn function.
y = (x > 0) - (x < 0)Print the answer.
print(y)