# C 程序：检查数字是正数还是负数

> 原文： [https://www.programiz.com/c-programming/examples/negative-positive-zero](https://www.programiz.com/c-programming/examples/negative-positive-zero)

#### 在此示例中，您将学习检查数字（由用户输入）是负数还是正数。

要理解此示例，您应该了解以下 [C 编程](/c-programming "C tutorial")主题：

*   [C 编程运算符](/c-programming/c-operators)
*   [C `if...else`语句](/c-programming/c-if-else-statement)

* * *

该程序从用户那里获取一个号码，并检查该号码是`positive`还是`negative`或`zero`。

* * *

## 使用`if...else`检查正负

```c
#include <stdio.h>
int main() {
    double num;
    printf("Enter a number: ");
    scanf("%lf", &num);
    if (num <= 0.0) {
        if (num == 0.0)
            printf("You entered 0.");
        else
            printf("You entered a negative number.");
    } else
        printf("You entered a positive number.");
    return 0;
} 
```

您还可以使用[嵌套](https://www.programiz.com/c-programming/c-if-else-statement) `if else` [语句](https://www.programiz.com/c-programming/c-if-else-statement)来解决此问题。

* * *

## 使用嵌套`if else`检查正数或负数

```c
#include <stdio.h>
int main() {
    double num;
    printf("Enter a number: ");
    scanf("%lf", &num);

    if (num < 0.0)
        printf("You entered a negative number.");
    else if (num > 0.0)
        printf("You entered a positive number.");
    else
        printf("You entered 0.");

    return 0;
} 
```

* * *

**输出 1**

```c
Enter a number: 12.3
You entered a positive number. 
```

**输出 2**

```c
Enter a number: 0
You entered 0. 
```