gpt4 book ai didi

c++ - 将罗马数字转换为小数c++

转载 作者:行者123 更新时间:2023-11-30 01:39:10 25 4
gpt4 key购买 nike

我正在尝试在 C++ 中将罗马数字转换为小数。

所以我的代码应该将罗马数字转换为小数,但它并不完全有效。

例如,VI为4,IV为6。
MCMXLVI 应该产生 1946,但如果我从左到右,我得到 -998,如果我从右到左,我得到 0。

我主要想知道我的思路对不对。

伪代码:

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

代码:

#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;
}

最佳答案

你教授提供的算法是对的。

一些提示:

for( double i = 0; i < RomanChars.length(); i++){
  • 那个从左到右循环。错误的方向。
  • double ?作为循环变量?不要那样做。 (不是你问题的原因,而是 baaad)

另一个答案已经指出你的 else 是错误的。如果我是你,我会考虑寻找一些优雅的东西来取代这种复制和粘贴狂欢。

如果您愿意——只是为了获得灵感——将您的罗马数字文字值存储在一个 std::map 中,您的转换循环将类似于这个循环(我示例中的 std::map 是 std::map<char, int> conversion):

int roman_to_int(std::string RomanChars){

RomanChars = convert_string(RomanChars);

int total = 0;
int max_value= 0;

for( size_t i = RomanChars.length()-1; i != std::string::npos; --i){

auto val = conversion.find(RomanChars[i]);
if(val != conversion.end())
{
if(val->second >= max_value)
{
total += val->second;
max_value = val->second;
} else {
total -= val->second;
}
}
}
return total;
}

关于c++ - 将罗马数字转换为小数c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com