为什么条件语句中的负数为真? [英] why negative number is taken as true in condition statement?

查看:73
本文介绍了为什么条件语句中的负数为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我对带有负数的条件语句感到困惑,如果在条件中仅给出负数,如(-1)则为true,但如果(-1> 0)则为false,请解释任何一个预先感谢

Here i am confused with condition statement which has negative number,if in the condition only negative number is given as if(-1) then it is true but if (-1>0) then it become false please explain any one thanks in advance

if(-1) // This true why and how?
if(-1>0)//This is false why and how

现在下面的代码有什么影响,请帮助理解

Now what is impact in below code please help to understand

#include <stdio.h>
#include <string.h>

main()
{
  char a[]="he";
  char b[]="she";
  if(strlen(a)-strlen(b)>0)//how it is true ?if(2-3>0)i.e if(-3>0) which is false
    //here why it is true                   
  {
    printf("-ve greater then 0 ");
  }
  else 
  {
    printf(" not greater then 0");
  }
}

推荐答案

if(-1)//这是正确的原因和方式?

if(-1) // This true why and how?

任何非零数字都将被评估为 true .

Any non-zero number is evaluated as true.

if(-1> 0)//这是错误的原因和方式

if(-1>0) //This is false why and how

-1 小于 0 ,这就是表达式 -1>0 评估为 false .

-1 is less than 0 that's why expression -1 > 0 evaluated to false.

if(strlen(a)-strlen(b)> 0)//它是如何正确的?if(2-3> 0)ie if(-3> 0)错误的//这里为何如此

if(strlen(a)-strlen(b)>0) //how it is true ?if(2-3>0)i.e if(-3>0) which is false //here why it is true

strlen 返回 size_t 类型,该类型为 unsigned . strlen(a)-strlen(b 的结果将是 unsigned int .但是 -1 的结果不是 unsigned >,因此在比较之前将其转换为 unsigned . strlen(a)-strlen(b)> 0 将导致比较 UINT_MAX -1> 0

strlen returns size_t type which is unsigned. The result of strlen(a)-strlen(b would be an unsigned int. But -1 in not unsigned, therefore it is converted to unsigned before comparison.strlen(a)-strlen(b)>0 will result in comparison UINT_MAX -1 > 0

这篇关于为什么条件语句中的负数为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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