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

如何让《C++ For Dummies》中的两段C++示例代码正常运行?

问题分析与解决

编译错误核心原因

  • 代码位置非法:第一个main()函数结束后的所有代码(从int i;开始)都写在了全局作用域里,C++只允许在全局区域进行变量/函数声明,不能直接写执行语句(比如std::cout、std::cin这类操作)。
  • 多余闭合大括号:代码末尾有一个无匹配的},属于语法错误。

修正后的代码

如果是两个独立的示例程序(C++程序只能有一个main()入口),分开编写如下:

示例1(原第一个main函数逻辑)

#include <iostream>

using namespace std;

int main()
{
    int x;
    x = 9;
    // 单独表达式无实际作用,可注释或删除
    // x > 10;
   
    char mychar;
    mychar = 'a';
    // mychar == 'A';
    // mychar != 'X';
   
    int i = 7;
    // (i < 10 || i > 100);
   
    if (x > 10)
    {
        std::cout << "Yuppers, it's greater than 10!" << std::endl;
    }
   
    std::cout << "Type any number:  ";
    std::cin >> i;
    if (i > 10)
    {
        std::cout << "It's greater than 10." << std::endl; 
    }
    else
    {
        std::cout << "It's not greater than 10." << std::endl;
    }
    return 0;
}

示例2(原全局区域的逻辑)

#include <iostream>

int main()
{
    int i;
    std::cout << "Type any number:  ";
    std::cin >> i;

    if (i > 10)
    {
        std::cout << "It's greater than 10." << std::endl;
    }
    else if (i == 10)
    {
        std::cout << "It's equal to 10" << std::endl;
    }
    else
    {
        std::cout << "It's less than 10." << std::endl;
    }
    return 0;
}

额外说明

原代码里那些单独的表达式(比如x > 10;)虽然语法合法,但计算结果会被直接丢弃,没有实际作用,建议注释或删除这类无用代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:05:41