gpt4 book ai didi

c++ - if 语句未评估为 false?程序给出奇怪的输出。为什么?

转载 作者:行者123 更新时间:2023-11-30 03:49:26 25 4
gpt4 key购买 nike

我必须编写一个程序来接收无符号输入并将它们放入一个无符号值数组中。如果输入了一个非无符号值,我会调用一个名为“die”的函数来输出一条错误消息,并终止程序。这是我为输入函数编写的代码:

void input(unsigned a[], unsigned elements){

cout << "Enter unsigned numbers one at a time, each followed by enter." << endl;

for (unsigned i = 0; i < elements;i++){
cout << "[" << i << "]: "; // outputs each index as user is inputting
cin >> a[i];

if ( sizeof(a[i]) != sizeof(unsigned) || a[i]<0 ){
die("Invalid input. Program will now exit.");
}
}
}

我已经检查过,die 函数可以自行正确执行它的工作。这是输入字符时此代码产生的输出:

Enter unsigned numbers one at a time, each followed by enter.
[0]: d
[1]: [2]: [3]: [4]: [5]: [6]: [7]: [8]: [9]: Press any key to continue . . .

如您所见,die 函数从未成功调用,因为它前面的 if 语句未计算为假。此外,我不确定为什么我的程序会为数组中的其余值显示空格。 只要收到的输入不是无符号的,我该如何重写 if 语句来调用 die 函数?

最佳答案

这是因为您的 if() 表达式永远无法在数学上评估为真。

让我们来看看:

if ( sizeof(a[i]) != sizeof(unsigned) || a[i]<0 ){

让我们把它分成两部分。第 1 部分:

a[i] 是一个unsigned。因此

sizeof(unsigned) != sizeof(unsigned)

永远是假的。

第 2 部分。因为 a[i] 是无符号的,所以它永远不会是负数,因此

a[i] < 0

也将始终为 false。

这就是您的 die() 永远不会执行的内容。

关于c++ - if 语句未评估为 false?程序给出奇怪的输出。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534387/

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