gpt4 book ai didi

c - 为什么条件语句中负数被视为真?

转载 作者:行者123 更新时间:2023-11-30 20:44:55 28 4
gpt4 key购买 nike

这里我对具有负数的条件语句感到困惑,如果在条件中仅给出负数,如 if(-1) 那么它是 true 但如果 (-1>0) 那么它就变成 false 请解释任何一个提前致谢

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");
}
}

最佳答案

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

任何非零数字都会被计算为 true

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

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

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类型为unsignedstrlen(a)-strlen(b的结果将是 unsigned int 。但是-1unsigned ,因此它被转换为unsigned比较之前。 strlen(a)-strlen(b)>0将导致比较 UINT_MAX -1 > 0

关于c - 为什么条件语句中负数被视为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673795/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com