C++程序:将正整数转换为英文单词
假设我们得到一个正整数。我们需要将这个数字用英文单词拼写出来;例如,如果输入数字“56”,输出将是“Fifty-Six”。转换范围最多为十亿。
因此,如果输入类似于 input = 5678,则输出将是 Five Thousand Six Hundred Seventy-Eight。
为了解决这个问题,我们将遵循以下步骤:
- 定义一个名为“numbers”的数组,其中包含以下键值对:{{"Billion", 1000000000},
- {"Million", 1000000},
- {"Thousand", 1000},
- {"Hundred", 100},
- {"Ninety", 90},
- {"Eighty", 80},
- {"Seventy", 70},
- {"Sixty", 60},
- {"Fifty", 50},
- {"Forty", 40},
- {"Thirty", 30},
- {"Twenty", 20},
- {"Nineteen", 19},
- {"Eighteen", 18},
- {"Seventeen", 17},
- {"Sixteen", 16},
- {"Fifteen", 15},
- {"Fourteen", 14},
- {"Thirteen", 13},
- {"Twelve", 12},
- {"Eleven", 11},
- {"Ten", 10},
- {"Nine", 9},
- {"Eight", 8},
- {"Seven", 7},
- {"Six", 6},
- {"Five", 5},
- {"Four", 4},
- {"Three", 3},
- {"Two", 2},
- {"One", 1}}
- 定义一个函数 solve()。它接收输入。
- 如果输入等于 0,则:
- 返回 "Zero"
- 对于 numbers 数组中的每个 num:
- 如果 num 的第二个值小于等于输入,则:
- 如果 num 的第二个值大于等于 100,则:
- result := solve(input / num 的第二个值)
- 如果 input > (input / num 的第二个值) * num 的第二个值,则:
- result := result + " " + solve(input - (input / num 的第二个值) * num 的第二个值)
- 否则:
- result := num 的第一个值 + ((如果 input > num 的第二个值,则: " " + solve(input - num 的第二个值),否则: " "))
- 跳出循环
- 如果 num 的第二个值大于等于 100,则:
- 如果 num 的第二个值小于等于输入,则:
- 返回 result
- 如果输入等于 0,则:
- solve(input)
示例
让我们看看下面的实现来更好地理解:
#include<bits/stdc++.h>
using namespace std;
vector<pair<string, int>> numbers{{"Billion", 1000000000},
{"Million", 1000000},
{"Thousand", 1000},
{"Hundred", 100},
{"Ninety", 90},
{"Eighty", 80},
{"Seventy", 70},
{"Sixty", 60},
{"Fifty", 50},
{"Forty", 40},
{"Thirty", 30},
{"Twenty", 20},
{"Nineteen", 19},
{"Eighteen", 18},
{"Seventeen", 17},
{"Sixteen", 16},
{"Fifteen", 15},
{"Fourteen", 14},
{"Thirteen", 13},
{"Twelve", 12},
{"Eleven", 11},
{"Ten", 10},
{"Nine", 9},
{"Eight", 8},
{"Seven", 7},
{"Six", 6},
{"Five", 5},
{"Four", 4},
{"Three", 3},
{"Two", 2},
{"One", 1}};
string solve(int input) {
if (input == 0) return "Zero";
string result;
for (auto& num : numbers) {
if (num.second <= input) {
if (num.second >= 100) {
result = solve(input / num.second) + " " + num.first;
if (input > (input / num.second) * num.second)
result += " " + solve(input - (input / num.second) * num.second);
} else {
result = num.first + (input > num.second ? " " + solve(input - num.second) : "");
}
break;
}
}
return result;
}
int main() {
cout<< solve(5678) <<endl;
return 0;
}输入
5678
输出
Five Thousand Six Hundred Seventy Eight
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP