簡體   English   中英

整數 C# 的所有數字的乘積

[英]Product of all digits of an integer number C#

我正在嘗試編寫一個遞歸程序,該程序將采用用戶輸入的數字,然后讓程序能夠計算整數的所有數字的乘積。 我已經確定了我希望程序如何運行,但我無法確定我應該如何運行我的循環來計算所有數字的乘積。 我發現您可以在 c 語言中通過使用 num%10 檢索 num 的最后一位數字來執行此操作,並使用 num/10 從整數末尾一次剝離一位數字。 我只是無法弄清楚如何在 C# 中實現它以及 if/else 結構應該如何。

下面是我為程序編寫的代碼,除了為 if/else 語句編寫代碼之外。 如果有人能夠指出我如何實現這一目標的正確方向,那將不勝感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace _3
{
class Tester
 {
    public static void Main(string[] args)
    {
        int length;
        Write("Enter a number: ");
        string num = Console.ReadLine();
        length = num.Length;
        int productofnum = Int32.Parse(num);
        productofnum = CalcProduct(productofnum);
        WriteLine("The product of all digits of the number {0} is {1}.",num, productofnum);
    }
    public static int CalcProduct(int num)
    {
        int length = num.ToString().Length;
        if (length == 0)
        {

        }
        else
        {
        }
        return num;
    }
 }
}

首先當使用遞歸函數時,你不應該在里面有任何循環。

您幾乎正確地構建了該方法的結構,但需要進行一些更改:

public static int CalcProduct(int num)
{
    int length = num.ToString().Length;
    if (length == 1)
    {
        return num;
    }
    return (num % 10) * CalcProduct(num / 10);
}

解釋:

當使用遞歸函數時,通常你需要調用你在返回中使用的函數 - 因此在使用 C# 的遞歸方法中遞歸閱讀更多。

建立在 Yonlif 的回答之上:如果您希望您的程序也能夠處理負數,請不要忘記在使用 div 和 mod 之前使用 Math.Abs​​(num)。 像這樣的東西:

public static int CalcProduct(int num)
{
    int _num=Math.Abs(num);
    int length = _num.ToString().Length;
    if (length == 1)
    {
        return _num;
    }
    return (_num % 10) * CalcProduct(_num / 10);
}

此外,這是尾遞歸方法,如果您喜歡它:

private  static int CalcProductTailRecHelper(int num, int res)
{
   int length = num.ToString().Length;
   if (length == 1)
   {
       return res;
   }
   return CalcProductTailRecHelper(num / 10, res*(num % 10));
}

private  static int CalcProductTailRec(int num){
    CalcProductTailRecHelper(Math.Abs(num), 1)
}

暫無
暫無

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

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