【问题标题】:How to compare each digit from two integers from the users c++如何比较来自用户c ++的两个整数的每个数字
【发布时间】:2015-05-20 20:52:57
【问题描述】:

我目前正在制作一个程序,要求用户输入两个整数并比较它们是否正确。我需要帮助编写这个程序。 (对不起,我是 C++ 新手)。

例如,这是我想要的输出。

输入你的正整数:123

输入你的正整数:124

数字 1:123

数字 2:124

比较次数:3

3 -- 4(不正确)

2 -- 2(正确)

1 -- 1(正确)

到目前为止我有这个代码:

void twoInt()
{
int first, second;


cout << "\n\nEnter your positive integer : ";
cin >> first;
cout << "\nEnter your positive integer : ";
cin >> second;

cout << "\n\nNumber 1: " << setw(10) << first;
cout << "\nNumber 2: " << setw(10) << second;

// how do i compare each digit that user has entered 
//through keyboard and compare them to first and second integer variable




fflush(stdin);
cin.get();


}

我应该使用哪个内置函数通过 for 循环进行比较?

提前致谢!任何提示和帮助将不胜感激!

【问题讨论】:

  • 提示:123%10==3124%10==4

标签: c++ integer compare


【解决方案1】:

退一步——你真的关心用户输入了整数吗?看起来你更关心的是用户输入了数字串,而你想对数字串进行分析。

如果你真的把他的输入读成一个数字串,那么,程序会更简单。

【讨论】:

    【解决方案2】:

    使用 std::to_string() 将两个数字转换为字符串 与您喜欢的算法进行比较:std::equal() 或 std::mismatch()

    您为什么不直接将它们作为整数进行比较?

    【讨论】:

      【解决方案3】:
       void twoInt()
       {
          int first, second;
          int fDigit;
          int sDigit;
      
          cout << "\n\nEnter your positive integer : ";
          cin >> first;
          cout << "\nEnter your positive integer : ";
          cin >> second;
      
          cout << "\n\nNumber 1: " << setw(10) << first;
          cout << "\nNumber 2: " << setw(10) << second;
          while ( (first ) && (second ))
          {
            fDigit = first % 10;
            first  = first/10;
            sDigit = second % 10;
            second = second / 10;
      
            if (fDigit == sDigit )
            {
              printf(" %d - % d Correct\n",fDigit,sDigit);
            }
            else
            {
              printf(" %d - % d  Incorrect\n",fDigit,sDigit);
            }
      
          }
          fflush(stdin);
      
          cin.get();
      
      }
      

      【讨论】:

        【解决方案4】:

        粗略的轮廓:

        使用递归函数。

        在函数中,获取每个数字的最后一位。

        d1 = N1 % 10
        d2 = N2 % 10
        

        比较它们并产生合适的输出。

        然后用剩下的数字再次调用函数:

        N1 = N1 / 10
        N2 = N2 / 10
        

        N1N2 为零时停止递归。

        【讨论】:

          猜你喜欢
          • 2014-10-25
          • 2021-12-28
          • 2019-09-11
          • 2012-06-05
          • 2020-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多