Creative Commons License Foxbond's Repo

/** (c) 2012 Michał (Foxbond) Chraniuk */
#include <iostream>
#include <stdlib.h>
#include <stdio.h> 
#include <string>
#include <conio.h> //_getch

using namespace std;

void cls(){system("cls");}


char roman[28][5]= {
		{"I"},
		{"II"},
		{"III"},
		{"IV"},
		{"V"},
		{"VI"},
		{"VII"},
		{"VIII"},
		{"IX"},
		{"X"},
		{"XX"},
		{"XXX"},
		{"XL"},
		{"L"},
		{"LX"},
		{"LXX"},
		{"LXXX"},
		{"XC"},
		{"C"},
		{"CC"},
		{"CCC"},
		{"CD"},
		{"D"},
		{"DC"},
		{"DCC"},
		{"DCCC"},
		{"CM"},
		{"M"}
	};

int decimal[28] = {
		1,
		2,
		3,
		4,
		5,
		6,
		7,
		8,
		9,
		10,
		20,
		30,
		40,
		50,
		60,
		70,
		80,
		90,
		100,
		200,
		300,
		400,
		500,
		600,
		700,
		800,
		900,
		1000
	};

int romanToDecimal (string _rom){

	int output = 0;
	int prev = 0;

	if (_rom.length() <= 0){
		return 0;
	}

	for (short i=0;_rom.length()>i;i++){
		if (_rom[i] == 'M'){
			output += 1000;
			if (prev < 1000){
				output -= prev*2;
			}
			prev = 1000;
		}else if (_rom[i] == 'D'){
			output += 500;
			if (prev < 500){
				output -= prev*2;
			}
			prev = 500;
		}
		else if (_rom[i] == 'C'){
			output += 100;
			if (prev < 100){
				output -= prev*2;
			}
			prev = 100;
		}
		else if (_rom[i] == 'L'){
			output += 50;
			if (prev < 50){
				output -= prev*2;
			}
			prev = 50;
		}
		else if (_rom[i] == 'X'){
			output += 10;
			if (prev < 10){
				output -= prev*2;
			}
			prev = 10;
		}
		else if (_rom[i] == 'V'){
			output += 5;
			if (prev < 5){
				output -= prev*2;
			}
			prev = 5;
		}
		else if (_rom[i] == 'I'){
			output += 1;
			if (prev < 1){
				output -= prev*2;
			}
			prev = 1;
		}else{
			return 0;
		}
	}

	return output;
}


string decimalToRoman (int _dec){
	
	string output = "";

	while(_dec >= 2000){
		output += 'M';
		_dec -= 1000;
	}

	for (short i=27;i>=0;i--){
		if (_dec >= decimal[i]){
			output += roman[i];
			_dec -= decimal[i];
		}
	}


	return output;
}

int main (){

	

	char opt='0';
	short _bufI=0;
	string _buf;
	int romToDecOutput = 0;

	do {
		cls();
		printf("1. Roman to decimal\n2. Decimal to roman\n0. Exit\n");
		//scanf("%i", opt);
		opt = _getch();
		
		if (opt == '1'){
			cls();
			printf("Roman: ");
			cin >> _buf;
			cls();
			romToDecOutput = romanToDecimal(_buf);
			if (romToDecOutput == 0){
				printf("%s Nie jest poprawna liczba rzymska!\nKliknij dowolny klawisz...\n", _buf.c_str());
			}else{
				printf("%s -> %i\nKliknij dowolny klawisz...\n", _buf.c_str(), romToDecOutput);
			}
			
			_getch();
		}else if (opt == '2'){
			cls();
			printf("Decimal: ");
			cin >> _bufI;
			cls();
			printf("%i -> %s\nKliknij dowolny klawisz...\n", _bufI, decimalToRoman(_bufI).c_str());
			_getch();
		}

	}while(opt != '0');
	
	return 0;
}

> Back