将值“01200000131”传递给此方法:
private static int sumOddVals(string barcode)
{
int cumulativeVal = 0;
for (int i = 0; i < barcode.Length; i++)
{
if (i % 2 != 0)
{
MessageBox.Show(string.Format("i is {0}; barcode{0} is {1}", i, barcode[i]));
cumulativeVal += Convert.ToInt16(barcode[i]);
}
}
MessageBox.Show(string.Format("Odd total is {0}", cumulativeVal));
return cumulativeVal;
}
...返回“244”
我期待它返回“4”。
第一个消息框显示了我期望看到的内容,即“1”,然后是“0”三次,然后是“3”,我期望加起来是“4”,而不是“244”。
您正在转换数字char
价值观int
's here:
cumulativeVal += Convert.ToInt16(barcode[i]); // Indexer on a string is a char
你想要的..是将数字的字符串表示形式转换为数字..而不是char
值..所以添加ToString()
:
cumulativeVal += Convert.ToInt16(barcode[i].ToString());
EDIT:
或者,正如评论中指出的:
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
结果:4。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)