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

เขียนโปรแกรม C เพื่อหาตัวเลขที่มากที่สุดและน้อยที่สุดในชุดข้อมูล

โจทย์

รับค่าจำนวนเต็ม 4 จำนวนจากผู้ใช้ แล้วหาค่าที่มากที่สุดและน้อยที่สุดในชุดข้อมูลนั้น

วิธีแก้ปัญหา

ใช้เงื่อนไข if เพื่อเปรียบเทียบค่าแต่ละตัวกับค่าสูงสุดและต่ำสุดปัจจุบัน ตรรกะคือ:

if (min > q) min = q;
else if (max < q) max = q;
if (min > r) min = r;
else if (max < r) max = r;
if (min > s) min = s;
else if (max < s) max = s;

โปรแกรมที่ 1: หาค่ามากที่สุดและน้อยที่สุดจาก 4 ตัวเลข

#include <stdio.h>
int main() {
    int minno, maxno, p, q, r, s;
    printf("enter any four numbers: ");
    scanf("%d %d %d %d", &p, &q, &r, &s);
    minno = p;
    maxno = p;
    if (minno > q) minno = q;
    else if (maxno < q) maxno = q;
    if (minno > r) minno = r;
    else if (maxno < r) maxno = r;
    if (minno > s) minno = s;
    else if (maxno < s) maxno = s;
    printf("Largest number from the given 4 numbers is: %d\n", maxno);
    printf("Smallest number from the given 4 numbers is: %d", minno);
    return 0;
}

ผลลัพธ์

enter any four numbers: 34 78 23 12
Largest number from the given 4 numbers is: 78
Smallest number from the given 4 numbers is: 12

โปรแกรมที่ 2: หาค่ามากที่สุดและน้อยที่สุดในอาร์เรย์

โปรแกรมนี้รับจำนวนสมาชิกและค่าของอาร์เรย์ แล้วหาค่าสูงสุดและต่ำสุด

#include <stdio.h>
int main() {
    int a[50], i, num, large, small;
    printf("Enter the number of elements: ");
    scanf("%d", &num);
    printf("Input the array elements:\n");
    for (i = 0; i < num; ++i)
        scanf("%d", &a[i]);
    large = small = a[0];
    for (i = 1; i < num; ++i) {
        if (a[i] > large) large = a[i];
        if (a[i] < small) small = a[i];
    }
    printf("small = %d\n", small);
    printf("large = %d\n", large);
    return 0;
}

ผลลัพธ์

Enter the number of elements: 8
Input the array elements: 1 2 6 4 8 9 3 9
small = 1
large = 9