C 解释条件运算符如何帮助计算数组中的负数和正数?

C 解释条件运算符如何帮助计算数组中的负数和正数?,c,C,我的困惑在于,在程序中,正数和负数的数量是如何通过编写所示的代码来计算的。 请解释这些代码 int num[5], i, neg = 0, pos = 0; printf("enter any 5 numbers"); for (i = 0; i <= 4; i++) scanf("%d", &num[i]); for (i = 0; i <= 4; i++) { num[i] < 0 ? neg++ : (pos++); } printf("\nne

我的困惑在于,在程序中,正数和负数的数量是如何通过编写所示的代码来计算的。 请解释这些代码

int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();
int num[5],i,neg=0,pos=0;
printf(“输入任意5个数字”);
对于(i=0;i
num[i]行

num[i]<0?neg++:(pos++);
num[i]=0),增加变量pos


希望这有帮助,因为大多数答案都解释了三元运算符,我不需要再做了。 neg++post递增neg变量的上一个值。pos++也是如此。
这是一个关于后期/前期增量的表达式。

用作表达式语句的三元运算符的计算结果与
if
语句类似:

num[i] < 0 ? neg++ : (pos++);
num[i]<0?neg++:(pos++);
相当于

if (num[i] < 0)
    neg++;
else
    pos++;
if(num[i]<0)
neg++;
其他的
pos++;
这种类型的编码被认为是不好的风格,发布的代码片段中还有其他问题:

  • 如果无法将输入转换为
    int
    ,则应检查
    scanf()
    的返回值,以避免未定义的行为


  • 循环索引应该用
    i<5
    与数组大小进行比较,而不是使用
    至于你的问题,你知道它是如何工作的吗?编译器不计算任何东西,仅供参考。也许我不知道!三元运算符的工作方式如下:
    条件?如果为真则执行:如果为假则执行
    num[i]
    if(num[i]感谢这些有价值的提示,我对如何检查scanf()返回值以及如何打开终端窗口以执行程序有点困惑。
    scanf()
    返回成功转换的次数。在您的情况下,如果整数存储在
    num[i]
    中,则应返回
    1
    。要打开终端窗口,请在Windows中使用开始菜单,运行
    cmd.exe
    if (num[i] < 0)
        neg++;
    else
        pos++;