如何比较来自用户c++的两个整数中的每个数字

How to compare each digit from two integers from the users c++

本文关键字:两个 数字 整数 用户 何比较 比较 c++      更新时间:2023-10-16

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

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

输入您的正整数:123

输入您的正整数:124

编号1:123

编号2:124

比较次数:3

3--4(错误)

2--2(正确)

1--1(正确)

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

void twoInt()
{
int first, second;

cout << "nnEnter your positive integer : ";
cin >> first;
cout << "nEnter your positive integer : ";
cin >> second;
cout << "nnNumber 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循环,我应该使用哪个内置函数进行比较?

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

大致轮廓:

使用递归函数。

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

d1 = N1 % 10
d2 = N2 % 10

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

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

N1 = N1 / 10
N2 = N2 / 10

N1N2为零时停止递归。

 void twoInt()
 {
    int first, second;
    int fDigit;
    int sDigit;
    cout << "nnEnter your positive integer : ";
    cin >> first;
    cout << "nEnter your positive integer : ";
    cin >> second;
    cout << "nnNumber 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 Correctn",fDigit,sDigit);
      }
      else
      {
        printf(" %d - % d  Incorrectn",fDigit,sDigit);
      }
    }
    fflush(stdin);
    cin.get();
}

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

你为什么不直接把它们作为星系进行比较呢?

退一步——您真的关心用户是否输入了整数吗?看起来更像是你关心的是用户已经输入了数字串,并且你想对字符串进行分析

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