【发布时间】:2014-07-10 10:07:32
【问题描述】:
在这里,我对具有负数的条件语句感到困惑,如果在条件中仅给出负数,则 if(-1) 则为真,但如果 (-1>0) 则为假,请解释任何一个在此先感谢
if(-1) // This true why and how?
if(-1>0)//This is false why and how
下面的代码有什么影响,请帮助理解
#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");
}
}
【问题讨论】:
-
您的以下代码的问题是由于有符号/无符号比较,与您上面的问题无关。见:“strlen(s1) - strlen(s2)” is never less than zero
-
您的
strlen()问题很有趣(也许是您的问题中唯一有趣的一点,而许多学习C 的文档都没有直接回答)。你应该只问这个,这样回答者就不会专注于前两个琐碎的问题。 -
这是一个size_t类型的无符号整数,返回strlen的值。所以会以无符号计算。改为
if((int)strlen(a)-(int)strlen(b)>0) -
if(2-3>0)i.e if(-3>0)-- 我不知道你是怎么得出这个结论的。2-3 > 0等价于-1 > 0。 -
if(strlen(a) > strlen(b))有什么问题?
标签: c if-statement negative-number