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

แปลง Integer เป็น Roman Numerals ใน C


ให้ decimal number n เราต้องแปลงเป็น Roman numeral ค่า n อยู่ในช่วง 1 ถึง 4000 นี่คือ Roman Numerals บางตัว

Number
Numeral
1I
4IV
5V
9IX
10X
40XL
50L
90XC
100C
400CD
500D
900CM
1000M
4000MMMM

เช่น n = 859 Roman Numeral จะเป็น DCCCLIX

เพื่อแก้ปัญหานี้ เราทำตามขั้นตอน

  • Define array เก็บ numeral และค่าที่สอดคล้อง สำหรับ list ที่ให้มา เรียกว่า nume array
  • ใช้ recursive approach ฟังก์ชัน decToRom() ใช้ nume array และ number num
  • decToRom() จะเป็นแบบนี้
    • ถ้า num ไม่ใช่ 0
      • max := หาค่าสูงสุดจาก nume array ที่ไม่เกิน num
      • append ค่าของ max นั้นลง result string
      • num := num − max value
      • decToRom(nume, num)

ตัวอย่าง

มาดู implementation เพื่อเข้าใจดีขึ้น −

#include<stdio.h>
typedef struct{
    char *sym;
    int val;
}numeral;
int maxNume(numeral *nu, int num){
    int i, index;
    for(i = 0; i<15; i++){//15 numerals in array
        if(nu[i].val <= num)
            index = i;
    }
    //gretest value numeral index, not greater than number
    return index;
}
void decToRoman(numeral *nu, int num){
    int max;
    if(num != 0){
        max = maxNume(nu, num);
        printf("%s", nu[max].sym);
        num -= nu[max].val;//decrease number
        decToRoman(nu, num);//recursively print numerals
    }
}
main(){
    int number;
    numeral nume[15] = {{"I",1},{"IV",4},{"V",5},{"IX",9}, {"X",10},{"XL",40},{"L",50},{"XC",90}, {"C",100},{"CD",400},{"D",500},{"CM",900},{"M",1000},{"MMMM",4000},{"V'",5000}};
    printf("Enter a decimal number: ");
    scanf("%d", &number);
    if(number >0 && number <= 5000){//checking input number
        printf("The Roman equivalent of %d is ", number);
        decToRoman(nume, number);
    }
    else{
        printf("Invalid Input");
    }
    printf("\n");
}

Input

570 3574

Output

DLXX MMMDLXXIV