这是我打印乘法表的C#代码
using System;
namespace MultiplicationTable
{
class Program
{
static void Main(string[] args)
{
dynamic value;
int i;
value = "123456789";
int num = Convert.ToInt32(Console.ReadLine());
foreach (char name in value)
{
i = Convert.ToInt32(name);
Console.WriteLine("{0} x {1} = {2}",i,num,i*num);
}
Console.ReadKey();
}
}
}
当我运行程序时, i 的值从 49 开始。 输入 6 的输出如下
答案 0 :(得分:12)
数字1的Unicode代码点为49. Convert.ToInt32()
with a char
argument returns the code point of said argument.
如果您的乘法值必须在字符串中,则快速解决此问题是在转换为int之前将每个数字转换为字符串:
i = Convert.ToInt32(name.ToString());
但是如果你在一系列数字上进行乘法运算,那么你可能最好使用int数组。如果您正在计算数字,则没有理由将它们存储在字符串中。
答案 1 :(得分:11)
因为字符1
的ASCII值为49
检查:
答案 2 :(得分:2)
检查以下输出
Console.WriteLine(Convert.ToInt32('1')); //49
Console.WriteLine(Convert.ToInt32("1")); //1
要修复程序,请先将char转换为字符串
i = Convert.ToInt32(Convert.ToString(name));
或者只是
i = Convert.ToInt32(name) - 48;