C++ 中的 Excel 表格列號
眾所周知,excel 列號為字母。它從 A 開始,在 Z 之後是 AA、AB、ZZ,然後又是 AAA、AAB、ZZZ,依此類推。因此,第 1 列是 A,第 27 列是 Z。此處我們將瞭解如何在給出列數的情況下獲取列字母。因此,如果列數為 80,那麼它將是 CB。
假設我們有一個數字 n,其值為 28,那麼我們需要用 26 取模。如果餘數為 0,則該數字為 26、52,依此類推。然後我們在輸出字串中放入 Z。n 的值變為 n/26 – 1。如果餘數不為零,那麼我們需要根據字串將相應的字元插入其中,然後令 n = n/26。最後,將列印字串的反轉。
示例 (C++)
#include<iostream> #include<algorithm> using namespace std; void showColumnLetters(int n) { string str = ""; while (n) { int rem = n%26; if (rem==0) { str += 'Z'; n = (n/26)-1; } else{ str += (rem-1) + 'A'; n = n/26; } } reverse(str.begin(), str.begin() + str.length()); cout << str << endl; } int main() { int n = 700; cout << "Cell name of " << n << " is: "; showColumnLetters(700); }
輸入
Cell number: 700
輸出
Enter cell number:700 Cell name of 700 is: ZX
廣告