Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

พิมพ์ m เท่าของ n แรกใน C# - Multiples of a Number

โปรแกรมพิมพ์จำนวนที่เป็นพหุคูณ (Multiples) ของตัวเลข n จำนวน m ตัวแรก

ตัวอย่างพื้นฐาน

using System;

public class Demo
{
    public static void Main()
    {
        int n = 6;      // ตัวเลขฐาน
        int m = 5;      // จำนวนพหุคูณที่ต้องการ

        for (int i = 1; i <= m; i++)
        {
            Console.WriteLine(n * i);
        }
    }
}

ผลลัพธ์

6
12
18
24
30

Generic Method

public static IEnumerable GetMultiples(int n, int count, int start = 1)
{
    for (int i = start; i < start + count; i++)
        yield return n * i;
}

// ใช้งาน
foreach (int m in GetMultiples(6, 5))
    Console.WriteLine(m);

// หรือ Materialize
var multiples = GetMultiples(7, 10).ToList();

LINQ Version

using System.Linq;

var multiples = Enumerable.Range(1, 5).Select(i => 6 * i);
var multiples2 = Enumerable.Range(1, 5).Select(i => i * 6).ToArray();

รองรับ Negative และ Zero

public static void PrintMultiples(int n, int m)
{
    if (m <= 0)
    {
        Console.WriteLine("Count must be positive");
        return;
    }

    for (int i = 1; i <= m; i++)
        Console.WriteLine(n * i);
}

// n = -3, m = 4 → -3, -6, -9, -12
// n = 0, m = 4 → 0, 0, 0, 0

การประยุกต์: Multiplication Table

public static void PrintMultiplicationTable(int n, int upTo = 12)
{
    Console.WriteLine($"Multiplication Table for {n}:");
    for (int i = 1; i <= upTo; i++)
    {
        Console.WriteLine($"{n} x {i,2} = {n * i,3}");
    }
}

ผลลัพธ์

Multiplication Table for 7:
7 x  1 =   7
7 x  2 =  14
7 x  3 =  21
...
7 x 12 =  84

กรณีใช้งานจริง

  • การสอนคณิตศาสตร์: Multiplication Table Generator
  • Signal Processing: Harmonic Frequencies (f, 2f, 3f...)
  • Game Dev: Spawn Points at Regular Intervals
  • Testing: Generate Test Cases with Regular Intervals