【发布时间】:2013-11-30 18:39:38
【问题描述】:
我制作了一个简单的二进制到十进制转换器,以前可以正常工作,我使用字符串变量来声明值,但现在意识到我需要将它们存储为整数,因为我想在 while 循环结构中添加验证用户的选择,以便他们只能输入 0 或 1。
但我现在有一个程序,上面写着Cannot convert from 'int' to 'System.IFormatProvider'.. 因为我是 C# 的初学者,
我不知道这意味着什么,以及如何解决这个问题,感谢任何帮助。如果有人想看,这是我的代码:
int iBinaryNum; //To store binary number
int iDecimalNum; //To store decimal numbers
//Validation of user choice & main program
while (iBinaryNum == 0 || iBinaryNum == 1)
{
Console.WriteLine("Enter the binary number you want to convert to decimal");
iBinaryNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Binary number you have entered is " + iBinaryNum);
iDecimalNum = Convert.ToInt32(iBinaryNum, 2);
Console.WriteLine("This converted into decimal is " + iDecimalNum);
}
//If it's not equal to 0 or 1
Console.WriteLine("Invalid binary number, Please re-enter");
//Prevent program from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
【问题讨论】:
-
您的代码没有意义。
-
为什么不呢?以前工作得很好,我曾经将 iBinaryNum 作为字符串 (sBinaryNum) 并且工作得很好,但是我需要验证用户的选择,所以我想也许将它转换为 int 可以让我这样做?那么哪一部分没有意义呢?
-
我认为这里不需要while循环,你可以使用if然后无效的控制台消息语句应该在else块中
-
@Sudhakar 是的,我可以这样做,但真的不会有所作为吗?我会试一试,我需要先修复这条线“iDecimalNum = Convert.ToInt32(iBinaryNum,2);”,只是不确定如何,我不太明白答案中的人想要告诉什么我,我是编程新手
标签: c# loops while-loop int