我完成了以下代码,将两个罗马数字加在一起。我只需要合并STDIN,这样用户就可以输入./a.out "<input.txt>"
来使用包含要添加的罗马数字的输入文件。它只需要两个输入,输入在一个简单的文本文件中。它永远不应该提示用户。代码在下面完成,只是没有上面的代码,它需要两个输入,输入在一个简单的文本文件中。
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
void predigit(char num1, char num2);
void postdigit(char c, int n);
char romanval[1000];
int p=0;
int main()
{
char rom1[30], rom2[30];
int a[30], l1, l2, i, k1, k2, dec,j;
long k;
printf("Enter the two roman numbers\n");
scanf("%s%s", &rom1,&rom2);
l1 =strlen(rom1);
for(i = 0; i < l1; i++)
{
switch (rom1[i])
{
case 'I': a[i] = 1;
break;
case 'V': a[i] = 5;
break;
case 'X': a[i] = 10;
break;
case 'L': a[i] = 50;
break;
case 'C': a[i] = 100;
break;
case 'D': dec = dec + 500;
break;
case 'M': a[i] = 1000;
break;
default : printf("Invalid choice");
break;
}
}
k1 = a[l1 - 1];
for(i = l1 - 1; i > 0; i--)
{
if(a[i] > a[i - 1])
{
k1 = k1 - a[i - 1];
}
if(a[i] <= a[i - 1])
{
k1 = k1 + a[i - 1];
}
}
l2 =strlen(rom2);
for(i = 0; i < l2; i++)
{
switch (rom2[i])
{
case 'I': a[i] = 1;
break;
case 'V': a[i] = 5;
break;
case 'X': a[i] = 10;
break;
case 'L': a[i] = 50;
break;
case 'C': a[i] = 100;
break;
case 'D': dec = dec + 500;
break;
case 'M': a[i] = 1000;
break;
default : printf("Invalid choice");
break;
}
}
k2 = a[l2 - 1];
for(i = l2 - 1; i > 0; i--)
{
if(a[i] > a[i - 1])
{
k2 = k2 - a[i - 1];
}
if(a[i] <= a[i - 1])
{
k2 = k2 + a[i - 1];
}
}
k= k1+k2;
printf("decimal equivalent is %d", k);
if (k <= 0)
{
printf("Invalid number");
return 0;
}
while (k != 0)
{
if (k >= 1000)
{
postdigit('M', k / 1000);
k = k - (k / 1000) * 1000;
}
else if (k >= 500)
{
if (k < (500 + 4 * 100))
{
postdigit('D', k / 500);
k = k - (k / 500) * 500;
}
else
{
predigit('C','M');
k = k - (1000-100);
}
}
else if (k >= 100)
{
if (k < (100 + 3 * 100))
{
postdigit('C', k / 100);
k = k - (k / 100) * 100;
}
else
{
predigit('L', 'D');
k = k - (500 - 100);
}
}
else if (k >= 50 )
{
if (k < (50 + 4 * 10))
{
postdigit('L', k / 50);
k = k - (k / 50) * 50;
}
else
{
predigit('X','C');
k = k - (100-10);
}
}
else if (k >= 10)
{
if (k < (10 + 3 * 10))
{
postdigit('X', k / 10);
k = k - (k / 10) * 10;
}
else
{
predigit('X','L');
k = k - (50 - 10);
}
}
else if (k >= 5)
{
if (k < (5 + 4 * 1))
{
postdigit('V', k / 5);
k = k - (k / 5) * 5;
}
else
{
predigit('I', 'X');
k = k - (10 - 1);
}
}
else if (k >= 1)
{
if (k < 4)
{
postdigit('I', k / 1);
k = k - (k / 1) * 1;
}
else
{
predigit('I', 'V');
k = k - (5 - 1);
}
}
}
printf("\nRoman number is: ");
for(j = 0; j < p; j++)
printf("%c", romanval[j]);
return 0;
}
void predigit(char num1, char num2)
{
romanval[p++] = num1;
romanval[p++] = num2;
}
void postdigit(char c, int n)
{
int j;
for (j = 0; j < n; j++)
romanval[p++] = c;
}