繁体   English   中英

如何从用户C ++的两个整数中比较每个数字

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

我目前正在制作一个程序,要求用户输入两个整数并比较它们是否正确。 我需要编码此程序的帮助。 (对不起,我是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循环进行比较?

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

粗略的轮廓:

使用递归函数。

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

d1 = N1 % 10
d2 = N2 % 10

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

然后使用其余的数字再次调用该函数:

N1 = N1 / 10
N2 = N2 / 10

N1N2为零时,停止递归。

 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();

}

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

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

退后一会儿-您实际上是否在乎用户是否输入了整数 看起来您更关心的是用户已输入数字字符串 ,并且您要对数字字符串进行分析。

如果您实际将他的输入读为一串数字 ,那么该程序将更加简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM