【C++】数値を序数表現にする
c++でライブラリをできるだけ使用せずに数値を序数表現にしてみようと思います.
きっかけはくいなちゃんのツイート.
プログラムで、英語で「3番目の値」「5番目の値」などと出力したい場合、「”the ” + n.toString() + “th value”」のように書きますよね。 ただこの場合、「1th」(1stが正しい)、「23th」(23rdが正しい)、のようにおかしいパターンが生じてしまいます。 こういうとき、みなさんならどう解決します?
— くいなちゃん (@kuina_ch) September 28, 2019
パターンを書き出してみよう.
そしてこのリスト,段落に入れたいのに入らないのはなぜ???WordPressわからんちん.
- 1st, 2nd, 3rd, 4th, 5th ,…., 10th
- 11th, 12th, 13th, 14th, …., 20th
- 21st, 22nd, 23rd, 24th, 25th, …., 30th
- 101st, 102nd, 103rd, 104th, …, 110th
- 111th, 112th, 113th, 114th, …, 120th
つまり,1の位が1でst
,2でnd
,3でrd
,4以上ならth
になるかと思いきや10の位が1だとすべてにおいてth
になる.
こんなめんどくさいルールにしたのは誰やねん.
まぁコードを書いてみた.
#include <iostream> #include <string> #include <vector> std::string suffix[] = {"th", "st", "nd", "rd"}; std::string addSuffix(int value){ std::string str; str += std::to_string(value); if((((value / 10) % 10) == 1) || // 10の位が1のパターン (((value % 10) & 0b1100) != 0)){ // 1の位が4以上のパターン str += suffix[0]; }else{ str += suffix[value % 10]; } return str; } void check(std::vector<int> _arg){ for(auto i : _arg){ std::cout << addSuffix(i) << std::endl; } } int main(){ check(std::vector<int>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 100, 101, 102, 103, 104, 105, 110, 111, 112, 113, 114, 115})); }
うんまぁこんなもんやろか
最近のコメント