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

初学C++:厘米转米代码无法输出正确值,请求问题排查

Fixing Your Centimeter-to-Meter Converter

Hey there! I can see exactly why your code isn't giving you the right results—let's break down the issues and fix them step by step.

The Main Problem: Using an Uninitialized Variable

The biggest issue here is that you're calculating the value of M before you read the user's input into CM.

When you declare int CM; without assigning a value to it, it holds a random "garbage" value from memory. Your code uses this garbage value to compute M first, and only then reads the user's input into CM—but by that point, M has already been set to a wrong value, and the input won't update it.

A Secondary (Optional) Improvement: Simplify the Conversion Logic

While your original calculation CM / CM2M + (CM % CM2M) * 0.01f technically works if CM is properly initialized, it's a bit more complicated than needed. You can simplify it by converting CM to a floating-point type first, then dividing by 100—this avoids having to handle integer division and remainders separately.

Fixed Code

Here's the corrected version of your code with explanations of the changes:

const int CM2M = 100;
int main() {
    using namespace std;
    int CM;
    
    // First, get the user's input
    cout << "Enter the height in CM: ";
    cin >> CM;
    
    // Now calculate the meters value, using a properly initialized CM
    float M = static_cast<float>(CM) / CM2M;
    
    // Output the result
    cout << "Your height in M is " << M << endl;
    return 0;
}

Key Changes:

  • Moved cin >> CM; before the calculation of M: This ensures CM has a valid user-provided value when we compute the meter conversion.
  • Simplified the conversion: Using static_cast<float>(CM) converts the integer CM to a float, so dividing by CM2M (100) will perform floating-point division instead of integer division, giving you the correct decimal result.

If you prefer to keep your original calculation logic, you just need to move it after the input step, like this:

const int CM2M = 100;
int main() {
    using namespace std;
    int CM;
    cout << "Enter the height in CM: ";
    cin >> CM;
    float M = CM / static_cast<float>(CM2M) + (CM % CM2M) * 0.01f;
    cout << "Your height in M is " << M << endl;
    return 0;
}

This will also work correctly because CM is now initialized before the calculation.

Important Note on Uninitialized Variables

Always remember: In C++, local variables (like CM in your main function) are not automatically initialized. If you use them before assigning a value, you'll get unpredictable results from garbage memory values. Always initialize or assign a value to a variable before using it!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:08:59