【问题标题】:Sum,product of digits not equal to 0 and number of digits...WITH SWITCH in C#总和,不等于 0 的数字乘积和位数......在 C# 中使用 SWITCH
【发布时间】:2018-04-02 12:21:40
【问题描述】:

我是编程新手,尤其是 C#,但我今年正在学习它,我意识到我确实喜欢它并且真的很想理解它。然而,我们的老师让我们自己学习。好的,没问题,互联网就是这么神奇。

所以我把这个练习作为家庭作业:

==== 计算不等于0的数字的和、乘积和整数的位数。====

问题是,我只知道如何使用 do while 和 if 来制作它,而且效果很好,但她希望我们也使用 SWITCH 来制作它,这就是我迷失的地方,因为我只是不知道如何构建案例(案例为0时很好,但是当数字或n!=为0时如何写案例?!)

我真的需要一些帮助,并且非常感谢 sosososo 提供的任何帮助!另外,您能否提供一个解释?太感谢了! :D

int n, s = 0, p = 1, d = 0, digit;
Console.Write("Number n : ");
n = Convert.ToInt32(Console.ReadLine());

if (n == 0)
    p = 0;
do
{
    digit = n % 10;
    s += digit;
    if (digit != 0)
        p *= digit;
    d++;
    n /= 10;
} while (n != 0);
Console.WriteLine("The sum of the digits is: {0} ", s);
Console.WriteLine("The product of the digits not equal to 0 is : {0} ", p);
Console.WriteLine("The number of the digits is: {0}", d);
Console.ReadKey();

【问题讨论】:

  • 如果我们有办法捕获未在 switch 构造中列出的情况...
  • 有趣的事实是,这至少是我今天读过的第二个具有相同主题的问题(数字的乘积......)......这里解释了开关:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
  • 告诉你的老师你想使用 Linq :) string str = "12345"; var s = str.Sum(x => x - '0'); var p = str.Select(x => x - '0').Aggregate((y, i) => y *= i);

标签: c# if-statement switch-statement product digits


【解决方案1】:

你不能在 switch/case 中打印所有可能的组合,但你至少可以在 "0" 和 "not 0" 之间进行区分:

switch(n)
{
     case 0: // n == 0
         p = 0;
         break;
     default: // this runs in any case but zero
         do
         {
             digit = n % 10;
             s += digit;
             if (digit != 0)
                 p *= digit;
             d++;
             n /= 10;
         } while (n != 0);
         break;
}

也许是这个,你的老师想告诉你的:default switch 的情况,基本上意味着“其他一切”。

关于您对 n 的分析...是的,您当然可以将其解析为 int 和除法/模数,但由于您是编程新手,也许您不知道您可以读取字符串 char -by-char 通过索引:

string input = Console.ReadLine();
foreach (char c in input)
{
    int digit = Convert.ToInt32(c);
    s += digit;
    p *= digit;
}

此 foreach 将逐个字符地遍历您的字符串并将下一个字符存储在 c 中。这段代码比你的 div/mod 版本更容易阅读。简单干净的代码有助于理解。

当像这样改变它时,你的开关看起来像:

switch (input.Length)
{
    case 0:
        p = 0;
        break;
    default:
        // the foreach loop from above
        break;
}

希望这会有所帮助,干杯,格里斯

【讨论】:

  • 谢谢你,格里斯!是的,这是....启发 xD 一个比我预期的更容易的解决方案
  • 接受答案是在这个网站上表达感谢的好方法。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-02-01
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
相关资源
最近更新 更多