簡體   English   中英

總和,數字乘積不等於0與數字的數量…在C#中為SWITCH

[英]Sum,product of digits not equal to 0 and number of digits…WITH SWITCH in C#

我是編程的新手,尤其是C#,但是我今年正在研究它,我意識到我確實喜歡它並且真的很想理解它。 但是,我們的老師讓我們自己學習。 好的,沒問題,互聯網是如此的令人驚奇。

因此,我將本練習作為家庭作業:

====計算總和,不等於0的位數與整數位數的乘積。====

問題是,我只知道如何同時使用if和if並使其完美運行,但她希望我們也可以使用SWITCH進行操作,這就是我迷失的地方,因為我只是不知道該如何構建案件(當case為0時很好,但是當digit或n!=等於0時我怎么寫大小寫?)

我真的需要一些幫助,非常感謝您給予的任何幫助! 另外,您能提供一個解釋嗎? 非常感謝! :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();

您不能在開關/盒中打印所有可能的組合,但是至少可以在“ 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情況,基本上意味着“其他所有東西”。

關於您對n的分析...當然可以,您可以將其解析為一個int以及該除數/模數的東西,但是由於您是編程的新手,也許您不知道您可以按字符讀取字符串-通過索引的char:

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

該foreach將遍歷字符串char-by-char並將下一個字符存儲在c 到目前為止,此代碼比div / mod版本更易於閱讀。 簡潔的代碼有助於理解。

像這樣更改它時,您的開關將如下所示:

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

希望這會有所幫助,歡呼,格里斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM