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

二进制转十进制分步输出问题:修正C#代码输出顺序错误

二进制转十进制分步输出修正方案

需求:输入二进制数(如10100)后,按指定格式展示转换步骤,要求步骤顺序、中间计算值都符合预期。

现有错误代码

String input = Console.ReadLine();
char[] array = input.ToCharArray();

int npower = array.Length;
npower--;
int npower1 = array.Length;
npower1--;
// Reverse since 16-8-4-2-1 not 1-2-4-8-16. 
Array.Reverse(array);
// Reverse since 16-8-4-2-1 not 1-2-4-8-16. 

/*
 * [0] = 1
 * [1] = 2
 * [2] = 4
 * etc
 */
int sum = 0;
int i = 0;
for (i=0; i < array.Length; i++)
{
    if (array[i] == '1')
    {
        // Method uses raising 2 to the power of the index. 
        if (i == 0)
        {
            sum += 1;
        }
        else
        {
            sum += (int)Math.Pow(2, i);
        }
    }
    Console.Write("(" + array[i]+"*2)^"+npower);
    npower--;
    if (npower > -1)
    {
        Console.Write(" + ");
    }
    
}
Console.WriteLine();
for (i = 0; i < array.Length; i++)
{
    Console.Write(" " + array[i] * (int)Math.Pow(2, npower1) + "");
    npower1--;
    if (npower1 > -1 )
    {
        Console.Write(" + ");
    }
}

Console.WriteLine();
Console.WriteLine(" = "+sum);
Console.ReadLine();

当前错误输出

10100
(0*2)^4 + (0*2)^3 + (1*2)^2 + (0*2)^1 + (1*2)^0
768 +  384 +  196 +  96 +  49
= 20

期望输出

10100
(1*2)^4 + (0*2)^3 + (1*2)^2 + (0*2)^1 + (0*2)^0
16 +  0 +  4 +  0 +  0
= 20

修正后的代码

string input = Console.ReadLine();
char[] array = input.ToCharArray();
int sum = 0;

// 输出第一步的转换表达式
for (int i = 0; i < array.Length; i++)
{
    int power = array.Length - 1 - i;
    Console.Write($"({array[i]}*2)^{power}");
    if (i < array.Length - 1)
    {
        Console.Write(" + ");
    }
}
Console.WriteLine();

// 输出第二步的计算值
for (int i = 0; i < array.Length; i++)
{
    int power = array.Length - 1 - i;
    int value = (array[i] - '0') * (int)Math.Pow(2, power);
    sum += value;
    Console.Write($" {value} ");
    if (i < array.Length - 1)
    {
        Console.Write("+ ");
    }
}
Console.WriteLine();

// 输出最终结果
Console.WriteLine($"= {sum}");
Console.ReadLine();

修正说明

  1. 移除数组反转:无需反转输入数组,直接按原始顺序遍历,保证步骤和输入二进制的位数顺序一致
  2. 幂次计算调整:每一位的幂次为数组长度-1-当前索引,对应二进制从高位到低位的权重(如10100的第一位1对应2^4)
  3. 修复中间值计算错误:之前直接用char类型计算会取到ASCII码值,现在先通过array[i]-'0'将字符转成整数0或1,再乘以对应权重
  4. 简化求和逻辑:在计算中间值的同时累加求和,避免重复遍历

内容的提问来源于stack exchange,提问作者Juan Charistheas Hawu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:20:27