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

如何在C#控制台应用中结合变量输出上标数字?

解决字符串插值中打印上标数字的问题

你的问题出在\xB{expressionExponent}的写法上——\xB是Unicode转义序列,要求后面必须跟固定的两位十六进制字符,不能直接插入变量。要在字符串插值中实现上标,得先把数字转换成对应的上标Unicode字符,再拼接到字符串里。

实现步骤:

  1. 0-9的数字对应固定的上标Unicode码点,先建立映射关系:

    • 上标0:\u2070
    • 上标1:\u00B9
    • 上标2:\u00B2
    • 上标3:\u00B3
    • 上标4-9:\u2074到\u2079
  2. 编写辅助方法,把数字转换成上标字符串:

using System.Collections.Generic;
using System.Linq;

// 数字到上标字符的映射字典
var superscriptMap = new Dictionary<char, char>
{
    {'0', '\u2070'},
    {'1', '\u00B9'},
    {'2', '\u00B2'},
    {'3', '\u00B3'},
    {'4', '\u2074'},
    {'5', '\u2075'},
    {'6', '\u2076'},
    {'7', '\u2077'},
    {'8', '\u2078'},
    {'9', '\u2079'}
};

// 将整数转换为上标字符串的方法
string ConvertToSuperscript(int number)
{
    return new string(number.ToString().Select(c => superscriptMap[c]).ToArray());
}
  1. 在字符串插值中使用这个方法:
Console.OutputEncoding = System.Text.Encoding.Unicode;

int expressionBase = 2;
int expressionExponent = 3;
int result = 8;

string superscriptExponent = ConvertToSuperscript(expressionExponent);
Console.WriteLine($"\n{expressionBase}{superscriptExponent} = {result}");

运行这段代码,就能正确输出2³ = 8。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:13:22