c - 如何比较无符号和有符号长变量?

标签 c output

当我遇到这个问题时,我正在准备面试。

#include<stdio.h>
int main()
{

    unsigned long a = 100;
    long b = -1;
    if(b>a)
        printf("YES");
    else
        printf("No");
}

要找到程序的输出。答案是 YES 谁能解释一下这是正确答案吗?我分析并发现,当 a 和 b 中至少有一个具有 unsigned 限定符时,答案是肯定的。当两者都很长时,它会打印 NO

编辑:

还有一个问题让我想了很多。这是代码

#include<stdio.h>
int main()
{

    float t = 1.0/3.0;
    if(t*3 == 1.0)
        printf("yes");
    else
        printf("no");

}

代码的答案是,但我无法破译它是如何获得的。此外,当我假设一个变量 a = t*3 并在 if 语句中比较它时,我得到的输出为 yes

我正在努力学习这些概念。所以请帮助我解释这两个程序如何产生各自的输出。

谢谢

最佳答案

当你进行比较时,编译器必须将两个操作数转换为相同的类型。 转换基于“等级”(大小)和符号。

If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type is converted to the type of the operand with unsigned integer type.

您将 unsigned longlong 进行比较。根据上面的规则,long b 被转换为 unsigned long,得到最大可能的正数。注意,实际位不会改变。 0xFFFFFFFF 作为 32 位有符号意味着 -1。作为 32 位无符号表示 4294967295。

至于 float ,== 运算符逐位比较 float 。但是你在除法和乘法中失去了一些精度。

关于c - 如何比较无符号和有符号长变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22332269/

相关文章:

c - 如何计算一个int变量中的1

java - 将自定义二维数组打印为矩阵

Python 正则表达式 - 字符串中的可选字段

java - 尝试响应命令行用户输入时出现问题

c - 关于类型,c 中的 `int (*)(int)` 是什么意思?

c - X 秒后终止程序 Linux C

在 C 中计算 Var Args 长度

ios - Swift 输出覆盖变量

python - 如何打印输出并保持在同一行(Python)?

c - FastCGI 在 c 中的分支