C++:地平线2019相关题

无符号数和有符号数相加

题目

#include "stdafx.h"
#include "stdlib.h"
#include <string>
#pragma warning( disable : 4996) 
#include <iostream>

using namespace std;

int main()
{
	unsigned int a = 6;
	int b = -20;
	(a + b > 6) ? puts(">6") : puts("<6");
	system("pause");
	return 0;
}

答案及解释

C++条件运算符:https://www.runoob.com/cplusplus/cpp-conditional-operator.html
输出:>6
解释:

int main()
{
	unsigned int a = 6;
	int b = -20;
	(a + b > 6) ? puts(">6") : puts("<6"); // a+b 按无符号数计算,结果为无符号数
	printf("a+b=%d
",(a+b));    // -14, a+b=fffffff2,补码表示,赋值给%d有符号整型数,所以为-14
	printf("a+b=%x
", (a + b)); // fffffff2
	system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/wt-seu/p/12831399.html