将整数转换为电子表格column_id时出错(1 到 'A',2 到 'B'...

Error in converting integer to spreadsheet column_id (1 to 'A', 2 to 'B'...)

本文关键字:出错 转换 整数 电子表格 column id      更新时间:2023-10-16

我想将输入的整数转换为电子表格column_id,即1至a,2至b,26至z,27至aa等。除26的倍数外,我的代码正正确地为所有输入运行,但我无法为其构成逻辑。它可能的逻辑是什么?

 #include<iostream>
 #include<algorithm> 
 using namespace std;
 int main(){
     int a,n;
     string b;
     cin>>a;
     b="";
     while(a){
         b+=((a%26)+'A'-1);
         a/=26;
     }
     reverse(b.begin(),b.end());
     cout<<b<<"n";
return 0;
}

输入 -

26

输出 -

A@

预期输出 -

Z

所以首先:为什么发生此错误?

如果您选择输入26作为a的值,则计算b的值如下:

b += ((26 % 26) + 'A' - 1); // or

b += (0 + 'A' - 1); // or

b += 'A' - 1; // which is equal to the '@' symbol

因此,显然您不会从字母中自我减去。但是,如果您在使用Modulo操作员之前降低a会发生什么?

a--;
while (a) {
  b+=static_cast<char>('A' + (a % 26)); 
  a/=26;
}

现在,这将适用于1-26的值,但对于26上方的值不起作用,如果您输入1 a,则不会输入循环。切换到DO-while循环将修复后者,但仍然会有问题。对于大于26的每个数字,您都会得到一个弦线,向前27个单元格(因此BA而不是AA)。但是,通过将a--移动到循环中,这也将被修复:

do { 
  a--;
  b+=static_cast<char>('A' + (a % 26)); // static_cast not needed just for clarity
  a/=26;
} while(a);

在这里是一个工作示例。