로마 숫자를 C++의 소수로 변환하려고합니다.로마 숫자를 십진수로 변환 C++
그래서 내 코드는 로마자를 십진수로 변환해야하지만 완전히 작동하지는 않습니다. 예를 들어
는, VI는 4이며, IV는 6
되고 MCMXLVI 1946을 양보해야하지만, 나는 오른쪽에서 왼쪽으로 가면 나는 왼쪽에서 오른쪽으로 가면 나는 -998을 얻고, 내가 공을 받고 있어요.
저는 주로 내 사고 과정이 올바른지 알고 싶습니다.
의사 :
total = 0
max_value_so_far = 0
for each character in the input string, going from right to left:
if character converted to decimal >= max_value_so_far
add character converted to decimal to total
update max_value_so_far
otherwise subtract character converted to decimal from total
코드 : 당신의 if
테스트 각각에 대해
#include "std_lib_facilities_5.h"
string convert_string(string input){
for(int i=0; i < input.length(); i++){
input[i] = toupper(input[i]);
}
return input;
}
int roman_to_int(string RomanChars){
RomanChars = convert_string(RomanChars);
int total = 0;
int max_value= 0;
int M,D,C,L,X,V,I;
M = 1000;
D = 500;
C = 100;
L = 50;
X = 10;
V = 5;
I = 1;
double StringLength =RomanChars.length();
for(int i = 0; i < StringLength; i++){
if(RomanChars[i] == 'M') {
if (M >= max_value) {
total += M;
max_value = M;
} else {
total -= M;
}
}
if(RomanChars[i] == 'D') {
if (D >= max_value) {
total += D;
max_value = D;
} else {
total -= D;
}
}
if(RomanChars[i] == 'C') {
if (C >= max_value) {
total += C;
max_value = C;
} else {
total -= C;
}
}
if(RomanChars[i] == 'L') {
if (L >= max_value) {
total += L;
max_value = L;
} else {
total -= L;
}
}
if(RomanChars[i] == 'X') {
if (X >= max_value) {
total += X;
max_value = X;
} else {
total -= X;
}
}
if(RomanChars[i] == 'V') {
if (V >= max_value) {
total += V;
max_value = V;
} else {
total -= V;
}
}
if(RomanChars[i] == 'I') {
if (I >= max_value) {
total += I;
max_value = I;
} else {
total -= I;
}
}
}
return total;
}
int main() {
string character;
int conversion = 0;
while(cin >> character){
conversion = roman_to_int(character);
cout << conversion <<endl;
}
return 0;
}
* 어떻게 작동하지 않습니까? 빌드 오류가 발생합니까? 충돌? 예기치 않은 결과가 있습니까? 제발 좀 더 자세히 설명해주세요. 그리고 [좋은 질문을하는 법을 읽어보십시오.] (http://stackoverflow.com/help/how-to-ask). 또한 Eric Lippert의 [작은 프로그램 디버깅 방법] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 읽고 디버거를 사용하여 단계별 실행 방법을 배우십시오. 당신의 코드. –
그게 내 부정적인 대답을주는 –
나는 내 생각 프로세스가 맞는지 알고 싶다. –