2013年9月29日 星期日

C#-內積


題目:

將兩向量做內積。


Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] a = { 1.2, 2.5, 3.0, 4.7, 5.1 }; // 宣告陣列A
            double[] b = { 5.9, 4.4, 3.1, 2.3, 1.8 }; // 宣告陣列B

            innerProduct(a, b); // 執行內積函式

            Console.ReadLine(); // 輸入值,用來讓程式暫停
        }

        static void innerProduct(double[] a, double[] b)
        {
            int i; // 宣告變數 i
            double sum = 0; // 宣告變數 sum 為0 ,用來表示內積
            double[] c = new double[a.Length]; // 宣告空陣列C
            for (i = 0; i < a.Length; i++) // 從0開始、到陣列A的長度
            {
                c[i] = a[i] * b[i]; // 每個陣列C=A、B向量的相乘
                sum += c[i]; // 將每個陣列C的值相加
//                Console.WriteLine("c[i" + i + "]=" + c[i] + " "); // 顯示每個陣C的值
            }
            Console.WriteLine("內積=" + sum + " "); // 顯示內積
        }
    }
}

檔案: InnerProduct.cs

沒有留言:

張貼留言