Hi. I've made a program to convert an integer to roman numeral. It runs fine for everything until I get to numbers 8 through 1. I'm not sure why the program doesn't want to output the I's properly. Any guidance on this would be much appreciated!
string CalcNumeral (int num)
{
int M=0; //1000
int D=0; //500
int C=0; //100
int L=0; //50
int X=0; //10
int IX=0; //9
int V=0; //5
int IV=0;//4
int I=0; //1
string numeral;
while (num >= 1000)
{
num = num - 1000;
M++;
}
if (num > 499 && num < 1000)
{
num = num - 500;
D++;
}
while ( num >=100)
{
num = num -100;
C++;
}
if (num > 49 && num < 100)
{
num = num -50;
L++;
}
while ( num > 9 )
{
num = num -10;
X++;
}
if (num == 9)
num = num-9;
IX++;
if ( num < 9 && num > 4)
{
num = num -5;
V++;
}
elseif (num == 4)
{
num = num - 4;
IV++;
}
else
{
for (int i =0; i < num; i++)
{
num = num -1;
I++;
}
}
for ( int i = 0; i < M; i++)
numeral = numeral + "M";
if (D == 1)
numeral = numeral + "D";
for (int i = 0; i < C; i++)
numeral = numeral + "C";
if (L == 1)
numeral = numeral + "L";
for ( int i = 0; i < X; i++)
numeral = numeral + "X";
if (IX ==1)
numeral = numeral + "IX";
if (V == 1)
numeral = numeral + "V";
elseif (IV == 1)
numeral = numeral + "IV";
else
{
for (int i = 0; i < I; i++)
numeral = numeral + "I";
}
return numeral;
To start with, line 64 in your code looks a bit suspicious?
And so do line 60 and 96
And the loop starting on line 62 : the interaction of the loop index and the num look suspicious, and I'm not sure you need a loop here? (you're decrementing by 1?)
Andy
PS fixing just those places, I now get
1 = I
2 = II
3 = III
4 = IV
5 = V
6 = VI
7 = VII
8 = VIII
9 = IX
10 = X
11 = XI
12 = XII
13 = XIII
14 = XIV
15 = XV
16 = XVI
17 = XVII
18 = XVIII
19 = XIX
20 = XX
Alright, I had a feeling that that the looping thing was causing some issues. However can you explain what you are fixing? This isn't for marks or anything but my own curiosity.
You're missing { }s, to the variable IX is always incremented
line 60 and 96
Neither of these elses is needed (I just removed them)
the loop starting on line 62
The problem is that you are decrementing the termination value at the same time as you're incrementing the index, so they end up meeting halfway.
For example, if num start off as 4, you increment the variable I to 1 and increment i to1 and decrement num to 3, then I=2, i=2, num=2. But now stepping the index to 3 terminates the loop. So you're left with I=2 when you wanted 4.
As the increment is 1 there's no need for this loop. I just replaced it with I = num; (by then, all that's left is the units)