发布于 2025-02-03 13:24:18 字数 633 浏览 0 评论 0原文

考虑以下代码

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  vector<int> a(n);
  int sum = 0;
  for (auto &it : a) {
    cin >> it;
    sum += it;
  }
  cout << sum << "\n";
  for (int i = 0; i < n; i++) {
    cout << a[i] << " ";
  }
  cout << endl;
}

输入,例如(或在k到k中大于int_max的内容)

5 1234567891564
1 2 3 4 5

使程序打印

0
0 0 0 0 0

实际发生了什么?我们根本不使用k的值。

Consider the following code

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  vector<int> a(n);
  int sum = 0;
  for (auto &it : a) {
    cin >> it;
    sum += it;
  }
  cout << sum << "\n";
  for (int i = 0; i < n; i++) {
    cout << a[i] << " ";
  }
  cout << endl;
}

Input like (or anything greater than INT_MAX into k)

5 1234567891564
1 2 3 4 5

makes the program print

0
0 0 0 0 0

What actually happens? We don't use the value of k at all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初熏 2025-02-10 13:24:18

您的代码实际上没有整数溢出。从更广泛的意义上讲,它存在,但是从更狭窄的意义上讲,整数溢出将发生:

int k = 1234567891564;

实际发生的是,在此行中,

cin >> n >> k;

操作员&gt;&gt;试图读取int int但失败。 1234567891564实际上从未分配给k。阅读输入时,将分配0。因此,k0出现。

一旦流处于错误状态,所有随后的调用operator&gt;也将默默失败。输入后,您应始终检查流的状态。例如:

 if (std::cin >> n) {
     // input succeeded use the value 
 } else {
     // input did not succeed. 
     std::cin.clear(); // reset all error flags
 }        

There is actually no integer overflow in your code. Well in a wider sense it there is, but in a more narrow sense integer overflow would happen for example with:

int k = 1234567891564;

What actually happens is that in this line

cin >> n >> k;

operator>> tries to read a int but fails. 1234567891564 is never actually assigned to k. When reading the input fails 0 will be assigned. Hence k comes out as 0.

Once the stream is in an error state, all subsequent calls to operator>> will silently fail as well. You should always check the state of the stream after taking input. For example:

 if (std::cin >> n) {
     // input succeeded use the value 
 } else {
     // input did not succeed. 
     std::cin.clear(); // reset all error flags
 }        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文