hello everyone, I would like to ask for some help with my assignement. My task is to make a program which is converting arabic numbers to roman numerals, but I can't use loops.
Gabriela_2
- 3 Contributors
- forum3 Replies
- 39 Views
- 1 Year Discussion Span
- comment Latest Post by tinstaafl
Reverend Jim 2,499
Show us what you have so far.
Gabriela_2
excuse me if it is a total bullshit, i'm a beginer in c++
#include <iostream>
using namespace std;
int main()
{
int n, a, b;
const char* r;
const char* m;
cin >> n;
if (n > 3000 || n <= 0)
{
cout << "Invalid Number!\n";
}
else
{
a = n / 1000;
if (a == 1)
{
r = "M";
}
if (a == 2)
{
r = "MM";
}
if (a == 3)
{
r = "MMM";
}
b = n / 100;
if (b == 1)
{
m = "C";
}
if (b == 2)
{
m = "CC";
}
if (b == 3)
{
m = "CCC";
}
if (b == 4)
{
m = "CD";
}
if (b == 5)
{
m = "D";
}
if (b == 6)
{
m = "DC";
}
if (b == 7)
{
m = "DCC";
}
if (b == 8)
{
m = "DCCC";
}
if (b == 9)
{
m = "CM";
}
cout << r << m;
}
return 0;
}
tinstaafl 1,060
A couple of things:
When you're programming in c++ it is much easier to use string
instead of char*
.
When you're joining strings(concatenating), since strings are immutable, a stringstream(<sstream>) is very handy. Otherwise, each time you join 2 strings you end up making a brand new string.
As for the logic, you seem to be on the right track.
One thing that can help is using the string(size_t, char)
constructor. Consider, once you know how many Thousands you'll need, you can simply say string(x,'M')
to represent that value.
Also if you subtract each leftmost digit once you've determined it's value, the rest is ready to be evaluated.
Consider this code segment which will handle the thousands and hundreds:
string ArabicToRoman(int input)
{
stringstream ss;
int temp = 0;
if (input > 3000 || input < 1)
{
return "Invalid Number!";
}
//If the input is 1000 or more or if the thousands digit is a 1,2, or 3
if (input > 999)
{
temp = input / 1000;
ss << string(temp,'M');
input -= temp * 1000;
}
//If the hundreds digit is a 9
if (input > 899)
{
ss << "CM";
input -= 900;
}
//If the hundreds digit is 5,6,7, or 8
else if (input > 499)
{
temp = (input / 100) % 5;
ss << "D" << string(temp, 'C');
input -= temp * 100;
}
//If the hundreds digit is a 4
else if (input > 399)
{
ss << "CD";
input -= 400;
}
//If the hundreds digit is a 1,2, or 3
else if (input > 99)
{
temp = input / 100;
ss << string(temp, 'C');
input -= temp * 100;
}
At this point you should be able to follow the pattern to finish it. The stringstream has a str() that will return the string represented in the stringstream(return ss.str();
).