繁体   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