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

为何输出56和54而非预期的6和8?C++代码问题咨询

问题解析:赋值字符'6'/'8'却输出54/56?

你遇到的问题核心是字符字面量与整数的区别:

  • 你写的int x = '6', y = '8';是把字符'6'和'8'赋值给int变量,而字符在C++中会被转换为对应的ASCII码值存储。
  • 字符'6'对应的ASCII码是54,'8'对应的ASCII码是56,所以直接输出int变量时,打印的就是这些数值。

解决方法

有两种方式可以得到你预期的输出:

  1. 直接赋值整数,去掉单引号:
#include <iostream>
using namespace std;

int main()
{
    int x = 6, y = 8;
    while(1){
        cout << "7" << endl;
        cout <<  y  << endl; 
        y += 1;
        cout << "7" << endl;
        cout <<  x  << endl; 
        x -= 1;
        }
}
  1. 保留字符赋值,但输出时强制转换为字符类型(或者把变量类型改成char):
#include <iostream>
using namespace std;

int main()
{
    int x = '6', y = '8';
    while(1){
        cout << "7" << endl;
        cout << static_cast<char>(y) << endl; 
        y += 1;
        cout << "7" << endl;
        cout << static_cast<char>(x) << endl; 
        x -= 1;
        }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:02:05