C ++:如何通过使用数组和放大器将普通话(字符串)分配给用户输入的数字。运营商问题

时间:2016-02-18 06:52:05

标签: c++ arrays operators

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

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时才会出现。

当我做1 - 11时,它会将yi添加到每个数字的开头。

当我做11 - 19时,它不起作用。

当我去99时,它变得更加凌乱。它还会在10,20,30等10的每个增量的末尾添加ling,当它不需要时。

所以我不明白int ten,int和if语句有什么问题......还要分配变量。我完全不知道该怎么做。我班上的很多孩子都使用if语句,但是我跳到了数组中,因为我不想做20个if语句。

请,谢谢你。

1 个答案:

答案 0 :(得分:0)

如果正确理解普通话的方式,这段代码将正确计数到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;
}