[英]Incorrect values when converting char digits to 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
截斷n /= 10
將截斷最低有效數字並最終在數字用盡時變為0。
您的代碼實際上是將char的十進制值相加。
看看https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
小數2和9分別為50和57。 在進行加法之前,需要將char轉換為int。
int val = (int)Char.GetNumericValue(a[i]);
您的問題是您要添加char
值。 請記住,char是一個整數值,代表ASCII字符。 當你加入a[i]
,以total
價值,你要添加的int
表示該值char
,編譯器自動將其丟。
問題在以下代碼行中:
total = total + a[i];
上面的代碼等於以下代碼行:
total += (int)a[i];
// If a[i] = '2', the character value of the ASCII table is 50.
// Then, (int)a[i] = 50.
要解決您的問題,您必須通過以下方式更改該行:
total = (int)Char.GetNumericValue(a[i]);
// If a[i] = '2'.
// Then, (int)Char.GetNumericValue(int)a[i] = 2.
您可以看到此答案,以了解如何將數字值從
char
轉換為int
。在此頁面上,您可以看到ASCII值表。
只是為了好玩,我想我可以看看是否可以使用LINQ在一行中完成它,這里是:
public static int AddWithLinq(int n)
{
return n.ToString().Aggregate(0, (total, c) => total + int.Parse(c.ToString()));
}
我認為這不是特別“干凈”的代碼,但充其量是很有教育意義的!
嘗試這個:
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 + (int)Char.GetNumericValue(a[i]);
}
return total;
}
將數字轉換為char始終返回ASCII代碼。因此,您可以使用GetNumericValue()方法獲取值而不是ASCII代碼
你應該int.TryParse
int num;
if (int.TryParse(a[i].ToString(), out num))
{
total += num;
}
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 += Convert.ToInt32(number[i].ToString());
}
return total;
}
您無需將數字轉換為字符串即可找到數字。 @juharr已經解釋了如何在循環中計算數字和總數。 以下是遞歸版本:
int addDigit(int total,int n)
{
return (n<10) ? total + n
: addDigit(total += n % 10,n /= 10);
}
可以使用addDigit(0,234233433)
調用並返回27。如果n
小於10,我們將計算最后一位。 否則,提取數字並將其添加到總數中,然后除以10並重復。
一個人可能會變得聰明,並使用currying擺脫最初的總數:
int addDigits(int i)=>addDigit(0,i);
addDigits(234233433)
還返回27;
如果數字已經是一個字符串,則可以利用以下事實:可以將字符串視為Char數組,並且可以將char隱式轉換為ints:
var total = "234233433".Sum(c=>c-'0');
只要總數不超過int.MaxValue
,就可以處理任意大的字符串,例如:
"99999999999999999999".Sum(x=>x-'0'); // 20 9s returns 180
除非數字已經是字符串形式,否則這將是無效的,也不會驗證內容是否為實際數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.