You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序编译成功但运行时C=0,求异常原因解析

Why Your C++ Program Keeps Outputting C=0 (and How to Fix It)

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/16 equals 0 (not 0.0625)
  • 1/4 equals 0 (not 0.25)
  • 1/2 equals 0 (not 0.5)
    This completely breaks your calculations for B, D, and C—you need to use floating-point literals (like 1.0 instead of 1) 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 using pow() and sqrt() without this include is undefined behavior.
  • I adjusted the output label from C^2 to C since you're printing the value of C, not its square. Feel free to change that back if it was a typo!

内容的提问来源于stack exchange,提问作者Shahla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:55:31