In C++, write a program that accepts a year written as a four-digit Arabic (ordi
ID: 3756176 • Letter: I
Question
In C++, write a program that accepts a year written as a four-digit Arabic (ordinary) numeral and outputs the year written in Roman numerals. Important Roman numerals are V for 5, X for 10, L for 50, C for 100, D for 500, and M for 1,000, Recall that some numbers are formed by using a kind of subtraction of one Roman “digit”; for example, IV is 4 produced as V minus I, XL is 40, CM is 900, and so on. A few sample years: MCM is 1900, MCML is 1950, MVMLX is 1960, MCMXI is 1940, MCMLXXXIX is 1989. Assume the year is between 1000 and 3000. Your program should include a loop that lets the user repeat this calculation until the user says she or he is done.
Explanation / Answer
#include <iostream>
#include <string>
std::string RomanNum(int arabic);
int numberOfDigits(int numb);
int First_digitof(int num);
int pwr(int base, int exponent);
int main()
{
char ans = 'y';
while (ans == 'y')
{
int numb;
std::cout << "Type in the numb you want to convert into RomanNum numerals: ";
while (true) {
std::cin >> numb;
if ((numb > 0) && (numb < 4000)) break;
std::cout << "Please give a numb between 1 and 3999: ";
}
std::cout << RomanNum(numb);
std::cout << " Do you want to convert another numb? (y/n) ";
std::cin >> ans;
std::cout << "______________ ";
}
}
std::string RomanNum(int arbic) {
if ((arbic < 1) || (arbic > 3999)) return ("Please give a numb between 1 and 3999.");
std::string roman;
while (arbic != 0)
{
int digit_Num = numberOfDigits(arbic);
int nxt_digit = First_digitof(arbic);
arbic -= nxt_digit * pwr(10, (digit_Num - 1));
char one, five;
if (digit_Num == 4) {; }
else if (digit_Num == 3) {; five = 'D'; }
else if (digit_Num == 2) {; five = 'L'; }
else if (digit_Num == 1) {; five = 'V'; }
if (nxt_digit <= 3) {
while (nxt_digit != 0) {
roman += one;
nxt_digit--;
}
}
else if (nxt_digit == 4) {
roman = roman + one + five;
}
else if (nxt_digit == 9) {
roman += one;
if (digit_Num == 3) roman += 'M';
else if (digit_Num == 2) roman += 'C';
else if (digit_Num == 1) roman += 'X';
}
else if ((nxt_digit <= 8) && (nxt_digit > 4)) {
roman += five;
while (nxt_digit != 5) {
roman += one;
nxt_digit--;
}
}
}
return roman;
}
int numberOfDigits(int numb) {
int digits = 0;
while (numb != 0) {
digits++;
numb /= 10;
}
return digits;
}
int First_digitof(int numb) {
return (numb / pwr(10, (numberOfDigits(numb) - 1)));
}
int pwr(int base, int exponent) {
int result = 1;
while (exponent != 0) {
result = result * base;
exponent--;
}
return result;
}