我完全不知所措
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
我期望的是:
7*3=21
但是我收到的却是:55*51=2805
我完全不知所措
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
7*3=21
但是我收到的却是:55*51=2805
55和51是它们在ascii表中的位置。 查看表格 - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png
尝试使用int.parse
int.Parse(temp[0].ToString());
。 - fishmong3r这是字符7和3的ASCII值。如果需要数字表示,则可以将每个字符转换为字符串,然后使用 Convert.ToString
:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
Console.WriteLine(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
int.Parse()
将一个字符或字符串转换为值。int tempc0 = int.Parse(temp[0].ToString());
int tempc1 = int.Parse(temp[1].ToString());
int product = tempc0 * tempc1; // 7 * 3 = 21
int.Parse()
不接受 char
作为参数,因此您需要先将其转换为 string
,或者使用 temp.SubString(0, 1)
。
这个方法可行,而且比使用 int.Parse()
或者 Convert.ToInt32()
更加计算效率高:
string temp = "73";
int tempc0 = temp[0] - '0';
int tempc1 = temp[1] - '0';
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
string temp = "73";
int tempc0 = Convert.ToInt32(temp.Substring(0, 1));
int tempc1 = Convert.ToInt32(temp.Substring(1, 1));
string temp = "73"
时,你的 temp[0]
和 temp[1]
是 char
值。Convert.ToInt32 Method(Char)
方法:
这意味着将一个将指定 Unicode 字符的值转换为等效的 32 位有符号整数。
char
转换成 int32
将会得到该字符的 Unicode 编码。temp[0]
和 temp[1]
值使用 .ToString()
方法。例如:string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
int tempc0 = Convert.ToInt32(temp[0].ToString()); int tempc1 = Convert.ToInt32(temp[1].ToString());
字符隐式地是数字,而该数字与您子字符串的 int 表示形式无关。 - Tim Schmeltertemp[0] - '0'
。请参阅我的答案以获取示例。 - JLRishe