C
Christopher Benson-Manica
Inspired by a thread on clc++, I decided to try it out...
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
int i;
int result=0;
int this;
int last=0;
if( argc != 2 ) {
printf( "No string specified\n" );
return( EXIT_FAILURE );
}
for( i=0 ; argv[1] != '\0' ; i++ ) {
switch( argv[1] ) {
case 'M':
this=1000;
break;
case 'D':
this=500;
break;
case 'C':
this=100;
break;
case 'L':
this=50;
break;
case 'X':
this=10;
break;
case 'V':
this=5;
break;
case 'I':
this=1;
break;
default:
printf( "Bad character %c\n", argv[1] );
return( EXIT_FAILURE );
}
result+=this;
if( this > last ) {
result-=2*last;
}
last=this;
}
printf( "Result is %d\n", result );
return( EXIT_SUCCESS );
}
This seems to work (and this time I didn't forget my header files
).
Questions:
A) Is it 100% legal, ANSI C?
B) Is there a more efficient way to implement it?
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
int i;
int result=0;
int this;
int last=0;
if( argc != 2 ) {
printf( "No string specified\n" );
return( EXIT_FAILURE );
}
for( i=0 ; argv[1] != '\0' ; i++ ) {
switch( argv[1] ) {
case 'M':
this=1000;
break;
case 'D':
this=500;
break;
case 'C':
this=100;
break;
case 'L':
this=50;
break;
case 'X':
this=10;
break;
case 'V':
this=5;
break;
case 'I':
this=1;
break;
default:
printf( "Bad character %c\n", argv[1] );
return( EXIT_FAILURE );
}
result+=this;
if( this > last ) {
result-=2*last;
}
last=this;
}
printf( "Result is %d\n", result );
return( EXIT_SUCCESS );
}
This seems to work (and this time I didn't forget my header files
Questions:
A) Is it 100% legal, ANSI C?
B) Is there a more efficient way to implement it?