C++程序编译成功但运行时C=0,求异常原因解析
Hey Shahla, let's break down exactly what's going wrong with your code and fix it step by step:
1. Uninitialized U0 ruins initial calculations
You declared U0 as a double but didn't assign a value to it before using it in A = U/U0. In C++, uninitialized variables hold random garbage values from memory, so your initial calculations for A, B, and D are based on invalid data right out the gate.
2. Integer division truncates your fractional results
Expressions like 1/16, 1/4, and 1/2 are integer divisions in C++. Since both operands are integers, the result gets chopped down to an integer:
1/16equals 0 (not 0.0625)1/4equals 0 (not 0.25)1/2equals 0 (not 0.5)
This completely breaks your calculations forB,D, andC—you need to use floating-point literals (like1.0instead of1) to force fractional division.
3. A, B, D aren't updated inside the loop
You calculate A, B, D once before the loop starts, but inside the loop, both U0 and U change. If you don't recalculate these values every iteration, you're using stale, incorrect numbers for every loop run.
Fixed Code
Here's the corrected version with all issues resolved:
#include <iostream> #include <cmath> // Required for pow() and sqrt() using namespace std; // Optional, simplifies access to cout int main() { double U0, U, C, A, B, D; U = 0.2; for (U0 = 0.2; U0 <= 1; U0 += 0.2) { if (U <= (4 * U0)) { // Recalculate values with current U0 and U each loop A = U / U0; B = 1 + 1.0 / (16 * pow(A, 2)); D = pow(B, 2) - (1.0 / 4) * A; C = (1.0 / 2) * (B + sqrt(D)); cout << " | U0 | " << U0 << " | U | " << U << " | C | " << C << endl; U += 0.2; } } return 0; }
Quick Extra Notes
- I added
<cmath>—your original code might have compiled accidentally, but usingpow()andsqrt()without this include is undefined behavior. - I adjusted the output label from
C^2toCsince you're printing the value ofC, not its square. Feel free to change that back if it was a typo!
内容的提问来源于stack exchange,提问作者Shahla

