将整数转换为电子表格column_id时出错(1 到 'A',2 到 'B'...
Error in converting integer to spreadsheet column_id (1 to 'A', 2 to 'B'...)
我想将输入的整数转换为电子表格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);
在这里是一个工作示例。
相关文章:
- 将链表转换为指针数组时出错
- 将类指针类型转换为键时出错
- 将代码从 Python 转换为 C++ 时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 编译时出错 - 从 DWORD 到 LPCVOID 的转换
- 在 Rcpp 中的字符串类型之间转换时出错
- 使用emscripten将c++文件转换为wasm时出错
- 从 uint8_t 到 int 的隐式转换出错了,当显式转换进展顺利时
- 将常量字符* 转换为字符时出错
- 浮点到整数转换出错(即使浮点数已经是整数)
- 在 C# 中从二进制值转换为双精度值时出错
- 将运算符<<与隐式转换的非基本数据类型一起使用时出错
- 为什么常量字符*到常量字符转换出错?
- 转换(常量字符*)变量出错
- 尝试将 C++11 代码转换为 C++03 时默认函数模板参数出错
- 将双精度转换为整数时出错
- 为什么我从字符转换为字符时出错
- 在Linux上构建Ogre时出错:缩小转换范围
- 编译C++代码时出错(转换无效)
- 链接libsodium时出错.a转换为共享对象