C# 程式可將列表中的所有數字相乘


首先,設定列表 −

List<int> myList = new List<int> () {
   5,
   10,
   7
};

現在,將變數的值設定為 1,它將幫助我們進行乘法 −

int prod = 1;

迴圈並獲取產品 −

foreach(int i in myList) {
   prod = prod*i;
}

以下為程式碼 −

示例

 即時演示

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      List<int> myList = new List<int>() {
         5,
         10,
         7
      };
      Console.WriteLine("List: ");
      foreach(int i in myList) {
         Console.WriteLine(i);
      }
      int prod = 1;
      foreach(int i in myList) {
         prod = prod*i;
      }
      Console.WriteLine("Product: {0}",prod);
   }
}

輸出

List:
5
10
7
Product: 350

更新日期:2020 年 6 月 22 日

954 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.