c# - 将 char 数字转换为 int 时的值不正确
问题描述
我的最终目标是取一个像 29 这样的数字,将其分开,然后将所得的两个整数相加。因此,例如,如果数字是 29,则答案将是 2 + 9 = 11。
当我调试时,我可以看到这些值被保留,但在这种情况下,其他值似乎也不正确 50、57。所以,我的答案是 107。我不知道这些值来自哪里我不知道从哪里开始修复它。
我的代码是:
class Program
{
static void Main(string[] args)
{
int a = 29;
int answer = addTwoDigits(a);
Console.ReadLine();
}
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + a[i];
}
return total;
}
}
解决方案
如前所述,您的代码问题是,当您转换为int
与各种数字不匹配的字符时,字符具有 ASCII 代码值。不要搞乱字符串和字符,而是使用好的旧数学。
public static int AddDigits(int n)
{
int total = 0;
while(n>0)
{
total += n % 10;
n /= 10;
}
return total;
}
以 10 为模将产生最低有效位,因为整数除法截断n /= 10
将截断最低有效位,并在您用完数字时最终变为 0。
推荐阅读
- wpf - Prism MVVM - 在 WPF 中的按钮单击命令上显示视图模型中的弹出窗口
- pymc3 - 为什么使用点积会恶化 PyMC3 的性能?
- python - python 正则表达式:字符串搜索日期
- javascript - Google 发布商代码障碍和无限滚动
- laravel - 为什么我在当前带有 id 的路线名称上出现错误
- python - 如何从 python unittest 中检索 TestResult 对象?
- xml - 如何从 XML 样式字符串中获取属性值
- graphviz - 如何更改 Graphviz 中相同等级节点的顺序?
- javascript - 如何在按钮单击时更新反应上下文提供程序状态
- python - 仅在表上更新一行