如何比较来自用户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 << "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
当N1
或N2
为零时停止递归。
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()
你为什么不直接把它们作为星系进行比较呢?
退一步——您真的关心用户是否输入了整数吗?看起来更像是你关心的是用户已经输入了数字串,并且你想对字符串进行分析。
如果你真的把他的输入读成数字串,那么程序会更简单。
相关文章:
- C++通过数字比较两个数字
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 在 txt 文件中显示前两个数字的程序
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 两个数字的对称配对功能
- 查找中间两个数字的正则表达式的匹配项
- 使用C++具有两个数字的最短路径算法.(C++)
- 将两个数字添加为链表
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 我应该如何使用remove_if删除两个数字范围内的元素
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- 子数组中两个数字的相同出现(连续)
- 如何使用位操作在单个整数中编码和解码两个数字
- 在 c++ 程序中调试链表以添加两个数字: 有人可以解释为什么 l3=l3->next;导致错误?
- 钻头以两个数字替换位
- C 如何在小数系统中添加两个数字
- 为什么我的代码不给最后两个数字
- 如何在给出前两个数字的级数中找到大于 x 的第 n 个最小子数组总和?
- 输入两个数字后程序关闭
- 代码是否交换数组的两个数字