[英]What is wrong with my code? There is some problem with printing correctly the numbers which sum of the digits end with the number 3 and the number 6
I want to know where is my so called fatal error because I am kinda newbie in coding with C# but in this case i really can not see anything wrong.我想知道我所谓的致命错误在哪里,因为我是使用C#编码的新手,但在这种情况下,我真的看不出有什么问题。
List<int> numbers = Console.ReadLine().Split(',').Select(int.Parse).ToList();
List<int> even = new List<int>();
List<int> odd = new List<int>();
List<int> sum3 = new List<int>();
List<int> sum6 = new List<int>();
int sum = 0;
foreach(var nums in numbers)
{
if(nums%2==0 && nums % 10 == 4 || nums % 10 == 2)
{
even.Add(nums);
}
else if(nums % 2 != 0 && nums % 10 == 5 || nums % 10 == 7)
{
odd.Add(nums);
}
int n = nums;
while (n != 0)
{
sum += n % 10;
n = n / 10;
}
if (sum % 10 == 3)
{
sum3.Add(nums);
}
else if (sum % 10 == 6)
{
sum6.Add(nums);
}
}
Console.WriteLine(String.Join(',',even));
Console.WriteLine(String.Join(',', odd));
Console.WriteLine(String.Join(',', sum3));
Console.WriteLine(String.Join(',', sum6));
You forget to change variable sum = 0
for each number.您忘记为每个数字更改变量sum = 0
。
Just update variable sum for each step inside your foreach
cycle.只需更新foreach
循环中每个步骤的变量总和。
Please review next code:请查看下一个代码:
int sum = 0;
foreach(var nums in numbers)
{
if(nums%2==0 && nums % 10 == 4 || nums % 10 == 2)
{
even.Add(nums);
}
else if(nums % 2 != 0 && nums % 10 == 5 || nums % 10 == 7)
{
odd.Add(nums);
}
sum = 0; // There is your issue (you forget about it)
int n = nums;
while (n != 0)
{
sum += n % 10;
n = n / 10;
}
if (sum % 10 == 3)
{
sum3.Add(nums);
}
else if (sum % 10 == 6)
{
sum6.Add(nums);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.