在CodeChef运行C++代码时触发SIGFPE运行时错误,如何解决该问题?
Hey there! Let's break down why you're getting that SIGFPE error and how to fix it.
First, SIGFPE in integer code almost always means division by zero. Looking at your code, the culprit is this line:
if (i % myvector[j].second != 0)
If myvector[j].second (which comes from your input y[i]) is zero, you're trying to compute i % 0—which is undefined and triggers the SIGFPE error.
Key Fixes & Improvements
Handle Division by Zero (y=0 Case)
Whenyis zero, there's no valid integeridivisible by zero. So we treat this as a special case where all positions should be set tox(since every position would satisfy the "not divisible by y" condition if it were valid). We add a check to avoid the modulo operation entirely whenyis zero.Replace Variable-Length Arrays (VLAs) with Vectors
VLAs likeint arr[n+1];aren't standard C++ and can cause unexpected behavior in some compilers. Usingvector<int>is safer, more flexible, and initializes values to zero by default (so we don't needmemsetanymore).Clean Up Loop Structure
Your nested do-while loops had a redundant variable declaration (int i=1;inside the inner loop) that shadowed the outer variable. Switching to for loops makes the code more readable and avoids this issue.Sum Only Relevant Positions
Your original code summed the entirearr(including index 0, which is unused). We now sum only positions 1 to n to avoid any accidental issues.
Corrected Code
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int T; cin >> T; while (T--) { int n, m; cin >> n >> m; vector<int> arr(n + 1, 0); // Initialize array with zeros vector<int> x(m), y(m); for (int i = 0; i < m; ++i) { cin >> x[i] >> y[i]; } vector<pair<int, int>> constraints; for (int i = 0; i < m; ++i) { constraints.emplace_back(x[i], y[i]); } sort(constraints.begin(), constraints.end()); // Sort by x ascending, then y for (const auto& p : constraints) { int x_val = p.first; int y_val = p.second; if (y_val == 0) { // Special case: set all positions to x_val fill(arr.begin() + 1, arr.end(), x_val); } else { for (int k = 1; k <= n; ++k) { if (k % y_val != 0) { arr[k] = x_val; } } } } int sum = 0; for (int k = 1; k <= n; ++k) { sum += arr[k]; } cout << sum << endl; } return 0; }
Explanation of Changes
- y=0 Handling: We use
fillto set all positions from 1 to n tox_valwhenyis zero, avoiding any division operation. - Vectors:
vector<int> arr(n+1, 0)creates an array of size n+1 initialized to zero, no need formemset. - Readable Loops: For loops make the flow clearer, and we use range-based for loops to iterate over constraints.
- Accurate Sum: We only sum positions 1 to n since arr[0] is unused and shouldn't contribute to the result.
This code should resolve the SIGFPE error and work correctly with your test cases.
内容的提问来源于stack exchange,提问作者Kuntal Manna

