为什么我的符号测试总是报告“否定”? [英] Why does my test of sign always report "negative"?

查看:156
本文介绍了为什么我的符号测试总是报告“否定”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序应打印数组元素的总和是正数还是负数:

The following program should print whether the sum of the elements of the array is positive or negative:

#include <stdio.h>

#define ARR_SIZE 5

int main()
{
   int array[ARR_SIZE] = {1,-2,3,4,-5};
   unsigned sum;
   int i;

   for(i=0, sum=0; i < ARR_SIZE; i++)
   {
         sum += array[i];
         printf("sum %d\n ", sum);
   }


         printf("%d\n",sum);
   if(sum>-1) printf("non negative\n");
   else printf("negative\n");
   return 0;
 }

该程序没有按预期执行;无论收到什么数组值,它都会打印负数。

The program doesn't do what it is supposed to; it prints 'negative' no matter what array values it receives.

例如,上面程序中写入的数组之和为1,因此我预计会有以下输出:

For example, the sum of the array written in the above program is 1, and therefore I expected the following output:

sum 1
sum -1
sum 2
sum 6
sum 1
1
non negative

输出为:

sum 1
sum -1
sum 2
sum 6
sum 1
1
negative

为什么我会得到这个输出?

Why do I get this output?

推荐答案

隐式类型转换:当您将变量定义为无符号并将其与负数进行比较时,该负数将隐式进行类型转换。正如我们所知,负数存储在两个恭维中,所以-1实际上变成了一个非常大的正数。现在无论您提供的大数字总是小于那么大的数字,这就是为什么您一直得到负面答案的原因。

Implicit Typecasting: When you define a variable as Unsigned and compare it with a negative number then that negative number is implicitly typecast. As we know negative numbers are stored in two's compliment, so -1 actually becomes a very big positive number. Now whatever the big number you supply it will always be less than that big number, that's why you are getting negative as answer all the time.

可能的解决方案:使用三元运算符处理+和 - 数字。
谢谢

Possible solution: use ternary operator to handle + and - numbers. Thanks

这篇关于为什么我的符号测试总是报告“否定”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆