【发布时间】:2015-09-13 10:48:27
【问题描述】:
我是 C# 新手,正在学习如何使用数组。我编写了一个小型控制台应用程序,可以将二进制数转换为十进制数;但是,我使用的语法似乎导致应用程序在某些时候使用整数的 unicode 指定而不是整数本身的真实值,因此 1 变为 49,0 变为 48。
如何以不同的方式编写应用程序以避免这种情况?谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Key in binary number and press Enter to calculate decimal equivalent");
string inputString = Console.ReadLine();
////This is supposed to change the user input into character array - possible issue here
char[] digitalState = inputString.ToArray();
int exponent = 0;
int numberBase = 2;
int digitIndex = inputString.Length - 1;
int decimalValue = 0;
int intermediateValue = 0;
//Calculates the decimal value of each binary digit by raising two to the power of the position of the digit. The result is then multiplied by the binary digit (i.e. 1 or 0, the "digitalState") to determine whether the result should be accumulated into the final result for the binary number as a whole ("decimalValue").
while (digitIndex > 0 || digitIndex == 0)
{
intermediateValue = (int)Math.Pow(numberBase, exponent) * digitalState[digitIndex]; //The calculation here gives the wrong result, possibly because of the unicode designation vs. true value issue
decimalValue = decimalValue + intermediateValue;
digitIndex--;
exponent++;
}
Console.WriteLine("The decimal equivalent of {0} is {1}", inputString, intermediateValue);
Console.ReadLine();
}
}
}
【问题讨论】:
-
我知道它并不能真正回答您的问题,但您的所有代码都可以简化为
Convert.ToInt32(inputString, 2)- 请参阅 this question。 -
不用担心。我正在尝试找出数组和循环结构的语法;因此不必要的笨拙代码。不过,您的方法仍然值得了解 - 谢谢。
-
具有讽刺意味的是,这个问题正确地引用了 Unicode,而一些答案却错误地引用了 ASCII。