为什么我的 C++ for 循环总是执行,尽管它的条件不满足?
Why does my C++ for loop always execute, despite its condition not being met?
来自 Java,我是 C++ 新手。
我无法弄清楚为什么下面的 for 循环总是执行,尽管 i
的初始值超过 n - 1
.
int maxProfit(vector<int>& prices) {
const int n = prices.size();
int profit = 0;
for(size_t i = 0; i < n - 1; i++) {
cout << "i: " + to_string(i) + ", n - 1: " + to_string(n - 1) + '\n';
const int diff = prices[i + 1] - prices[i];
if(diff > 0) { profit += diff; }
}
return profit;
}
我得到的输出(由于打印语句)是:
i: 0, n - 1: -1
,后面是:
AddressSanitizer:DEADLYSIGNAL
=================================================================
==32==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000004 (pc 0x000000382c25 bp 0x7ffd70e65f70 sp 0x7ffd70e65d00 T0)
==32==The signal is caused by a READ memory access.
==32==Hint: address points to the zero page.
#3 0x7f6ee7f0682f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
AddressSanitizer can not provide additional info.
==32==ABORTING
也许我没有看到什么,但是有人可以告诉我为什么 for 循环执行,尽管 for 循环中的条件被违反了吗?
我不确定这是哪个版本的 C++。这是来自 LeetCode 的在线编辑器。
Java 没有无符号类型,但 C++ 有。如果 n == 0
则 n - 1
在数学上是 -1
,但 -1
不是无符号值。在这种情况下发生的是结果 环绕 并且 -1
实际上等于最大可能的无符号值。将您的代码更改为此以获得预期结果
for(size_t i = 0; i + 1 < n; i++) {
现在没有负数了。
来自 Java,我是 C++ 新手。
我无法弄清楚为什么下面的 for 循环总是执行,尽管 i
的初始值超过 n - 1
.
int maxProfit(vector<int>& prices) {
const int n = prices.size();
int profit = 0;
for(size_t i = 0; i < n - 1; i++) {
cout << "i: " + to_string(i) + ", n - 1: " + to_string(n - 1) + '\n';
const int diff = prices[i + 1] - prices[i];
if(diff > 0) { profit += diff; }
}
return profit;
}
我得到的输出(由于打印语句)是:
i: 0, n - 1: -1
,后面是:
AddressSanitizer:DEADLYSIGNAL
=================================================================
==32==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000004 (pc 0x000000382c25 bp 0x7ffd70e65f70 sp 0x7ffd70e65d00 T0)
==32==The signal is caused by a READ memory access.
==32==Hint: address points to the zero page.
#3 0x7f6ee7f0682f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
AddressSanitizer can not provide additional info.
==32==ABORTING
也许我没有看到什么,但是有人可以告诉我为什么 for 循环执行,尽管 for 循环中的条件被违反了吗?
我不确定这是哪个版本的 C++。这是来自 LeetCode 的在线编辑器。
Java 没有无符号类型,但 C++ 有。如果 n == 0
则 n - 1
在数学上是 -1
,但 -1
不是无符号值。在这种情况下发生的是结果 环绕 并且 -1
实际上等于最大可能的无符号值。将您的代码更改为此以获得预期结果
for(size_t i = 0; i + 1 < n; i++) {
现在没有负数了。