C++:如何将普通话(字符串)分配给用户使用数组输入的数字 &运算符问题
C++ : How to assign mandarin (strings) to numbers a user inputed by using an array & Operator Issues
这是我的代码(底部的问题描述):
int x = 0;
int y = 0;
int z = 0;
const size_t MANDARIN_SIZE = 11;
const char *mandarin[MANDARIN_SIZE] = {" ling "," yi "," er "," san "," se "," wu "," liu "," qi "," ba "," jiu "," shi "};
cout << "Please enter a number that you want to count up to in Mandarin." << endl;
cin >> x;
if (!cin) return 1;
cout << "Please enter what number to start with:" << endl;
cin >> y;
if (!cin) return 1;
cout << "What step size do you want to use?n";
cin >> z;
if (!cin) return 1;
for ( ; y<=x; y=y+z)
{
int tens = y / 10;
int ones = y % 10;
if ( x < 11 )
cout << y << mandarin[ones] << "n";
if ( x > 10 && x < 19 )
cout << y << " shi " << mandarin[ones] << "n";
if ( x >= 20 )
cout << y << mandarin[tens] << " shi " << mandarin[ones] << "n";
}
该程序的目标是让用户输入他们希望程序计数的数字、计数序列开始的数字以及它计数的增量。
当我做 1 - 10 时,一切都很好,直到 10 当它应该被 shi 时放 ling。
当我做 1 - 11 时,它会在每个数字的开头加上 yi。
当我做 11 - 19 时,它不起作用。
当我去99时,它变得更加混乱。当不需要时,它还会在 10、20、30 等每个增量的末尾添加 ling。
所以我不明白 int tens、int 和 if 语句有什么问题......还分配变量。我完全不知道该怎么做。我班上的很多孩子都使用 if 语句,但我直接跳进数组,因为我不想做 20 个 if 语句。
请,谢谢。
如果正确理解普通话的计数方式,此代码将正确计数到 99。我在这里使用了一个 std::map,我认为它比你的方法更合适和 c++ 风格。
#include <map>
#include <iostream>
#include <string>
int main () {
std::map<int,std::string> mandarin_numbers;
mandarin_numbers[0] = "ling";
mandarin_numbers[1] = "yi";
mandarin_numbers[2] = "er";
mandarin_numbers[3] = "san";
mandarin_numbers[4] = "se";
mandarin_numbers[5] = "wu";
mandarin_numbers[6] = "liu";
mandarin_numbers[7] = "qi";
mandarin_numbers[8] = "ba";
mandarin_numbers[9] = "jiu";
mandarin_numbers[10] = "shi";
// in c++11 you could more simply: std::map<unsigned int,std::string,> mandarin_numbers {{0,"ling"}, etc..};
std::cout << "Please enter a number that you want to count up to in Mandarin." << std::endl;
int x = 0;
std::cin >> x;
std::cout << "Please enter what number to start with:" << std::endl;
int y = 0;
std::cin >> y;
std::cout << "What step size do you want to use?" << std::endl;
int z = 0;
std::cin >> z;
for ( ;y<=x; y=y+z) {
int tens = y / 10;
int ones = y % 10;
std::cout << mandarin_numbers[tens] << " " << mandarin_numbers[10] << " "
<< mandarin_numbers[ones] << std::endl;
}
return 0;
}
相关文章:
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- C++逗号分隔的输入数组代码过早退出
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 cin 输入数组值
- 与 C++ 中一行中的用户输入数组元素相关的问题
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- 如何在C 中动态输入数组
- 我想添加两个字符串类型的矩阵.用户将不会输入行数或列的数量.用户将仅输入数组
- 测试用户输入数组中的重复项的最有效方法是什么?
- 在用户输入数组中查找元音
- 如何将用户输入数组值移动到数组末尾并将其设置为 0
- 函数是否可以用较小的输入数组编写输入数组
- C++ 将数字输入数组并输出
- 需要帮助传递数组和输入数组
- 用户输入数组大小(N).从 0 到 N 的数字填充数组
- 输入int之后的字符的c++输入数组
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- 在C 函数中声明输入数组的大小
- 在 cpp 中使用 getline 输入数组中的空格分隔数字