c# - 如何将 char 从字符串转换为 double 等?
问题描述
我需要一个程序来告诉我所有小于用户定义的 10到1.000.000 之间的数字(如果可能的话,在 10 到无限之间)。即使 vs 在编辑器中没有显示任何错误,当我运行它时,它也会显示以下错误消息:“System.InvalidCastException: 'Invalid cast from 'Char' to 'Double'.'”在其中一个
calculation = Math.Pow(Convert.ToDouble(strI[0]), 1.0);
我尝试了其他方法将字符转换为双精度,但它们给出相同或其他错误消息或将它们转换错误。此外,我几乎可以肯定我可以使用比使用 switch 语句更紧凑的方法来确定数字的位数(也许可以读取数字的长度?)但不知道如何。
//prints out all the disarium numbers lower than a user defined number
static void Main(string[] args)
{
//assigns the variables
string number , strI;
double calculation = 0;
//asks the user for string number
Console.WriteLine("Give a number between 10 and 1.000.000. This program will tell you all the disarium numbers lower than the given number.");
number = Console.ReadLine();
//calcules all the disarium numbers lower than string number
for (int I = 10;I < Convert.ToInt32(number);I++)
{
strI = Convert.ToString(I);
switch (strI.Length)
{
case 1:
calculation = Math.Pow(Convert.ToDouble(strI[0]), 1.0);
break;
case 2:
calculation = Math.Pow(Convert.ToDouble(strI[0]), 1.0) + Math.Pow(Convert.ToDouble(strI[1]), 2.0);
break;
case 3:
calculation = Math.Pow(Convert.ToDouble(strI[0]), 1.0) + Math.Pow(Convert.ToDouble(strI[1]), 2.0) + Math.Pow(Convert.ToDouble(strI[2]), 3.0);
break;
case 4:
calculation = Math.Pow(Convert.ToDouble(strI[0]), 1.0) + Math.Pow(Convert.ToDouble(strI[1]), 2.0) + Math.Pow(Convert.ToDouble(strI[2]), 3.0) + Math.Pow(Convert.ToDouble(strI[3]), 4.0);
break;
case 5:
Console.WriteLine("...");
break;
case 6:
Console.WriteLine("...");
break;
case 7:
Console.WriteLine("...");
break;
default:
break;
}
//Prints out all the desarium numbers below string number
if (calculation == Convert.ToDouble(I))
{
Console.WriteLine(I + " is a disarium number.");
}
}
//Keeps the command line from closing
Console.ReadLine();
Console.WriteLine("Press ENTER to close the program.");
}
如果还不够清楚。我基本上从 for 循环中用 i 的值创建了一个新变量,但是作为字符串(我这样做是为了可以逐个字符地遍历数字)
strI = Convert.ToString(I);
然后我使用 switch 语句确定输入数字的位数。
之后,我创建一个变量,它是第 i 小数 1 的第一个字符,第 i 个小数 2 的第 2 个字符......直到它达到位数
Math.Pow(Convert.ToDouble(strI[0]), 1.0) + Math.Pow(Convert.ToDouble(strI[1]), 2.0)...
最后我将 i 与计算结果进行比较
if (calculation == Convert.ToDouble(I))
如果变量匹配,则为 disarium 编号。
提前致谢!
~ 伊曼纽尔
解决方案
Convert.ToDouble(strI[0].ToString())
这将修复您的计算,以便它们不会引发异常。尽管由于浮点数是如何通过舍入存储的,但在最后进行浮点比较可能会出现问题。我建议您在添加之前将 Math.Pow 的每个结果转换回 int/long。如果 int/long 不够大,您可能需要 BigInteger(System.Numerics 命名空间)之类的东西。
此外,该 switch 语句可以替换为...
strI = Convert.ToString(I);
calculation = 0;
for(int i = 0; i < strI.Length; i++)
{
calculation += Math.Pow(Convert.ToDouble(strI[i].ToString()));
}
if (calculation == Convert.ToDouble(I))
...