-5

我正在做一个计数程序,我需要自己对 x 数的所有数字进行复数。

例如:号码 123456789;

1*2*3*4*5*6*7*8*9=362,880

4

1 回答 1

2

评论中提供了一个很好的解决方案,但如果您想弄清楚您实际在做什么,则不太容易理解。以下代码有点冗长,但向您展示了每一步实际发生的情况:

using System;

class MainClass {
  public static void Main () {
    int myNumber = 123456789;  //store original number
    int newNumber = (int)Math.Abs(myNumber);  //changes the number to positive if it is negative to prevent string formatting errors.
    int product = 1; //store product start point
    string myString = newNumber.ToString(); //convert number to string

    foreach(char number in myString){  //loop through string
      string numberString = number.ToString();  //convert chars to strings to ensure proper output
      int oneDigit = Convert.ToInt32(numberString); //convert strings to integers
      product = product*oneDigit;  //multiply each integer by the product and set that as the new product
    }
    if(myNumber < 0){product = -product;} 
    //if the number is negative, the result will be negative, since it is a negative followed by a bunch of positives.
    //If you want your result to reflect that, add the above line to account for negative numbers.
    Console.WriteLine(product);  //display product
  }
}

Output>>> 362880  //The output that was printed.

所以我们首先将我们的数字转换成一个字符串,这样我们就可以遍历它。然后我们有一个foreach循环遍历字符串中的每个字符,将其转换为整数,并将其乘以先前数字的乘积。每次执行新的乘法时,乘积都会更新,直到到达数字末尾时,您拥有所有数字的乘积。这是一个熟悉循环的好项目。我建议使用它的变体,例如将每个数字乘以原始数字,仅将 3 的倍数相乘,仅将小于 5 的数字相乘,或者仅将前 5 个数字相乘以更好地处理发生的事情环形。

于 2019-03-27T18:54:04.010 回答