C++:如何将普通话(字符串)分配给用户使用数组输入的数字 &运算符问题

C++ : How to assign mandarin (strings) to numbers a user inputed by using an array & Operator Issues

本文关键字:输入 数组 数字 问题 运算符 给用户 分配 普通话 字符串 C++      更新时间:2023-10-16

这是我的代码(底部的问题描述):

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;
}