比较C++变量的最有效方法

Most Efficient way to compare variables in C++

本文关键字:有效 方法 C++ 变量 比较      更新时间:2023-10-16

我有一个任务是为下面的问题制作代码。

编写一个彩票游戏应用程序,该应用程序将生成三个随机数,每个随机数介于 0 和 9 之间。用户应该猜测三个数字,程序应该将每个用户的猜测与三个随机进行比较,并根据他们是否得到以下结果显示适当的输出:

  • 任何匹配的人
  • 两个匹配
  • 三匹配,不按顺序
  • 三个精确匹配的顺序
  • 或根本没有匹配项

我一直在尝试不同的方法来做到这一点,我发现的一种方法是使用 if else if 语句,但代码看起来效率很低。

我尝试做的另一种方法是使用 for 循环,但随后存在逻辑错误。

我使用以下代码。

int inputarray[3];
int randomnumberarray[3];
//here goes simple if condition for checking case of all same numbers in exact order//
for ( int i = 0 ; i < 3 ; i ++ ) /*this condition is applied after checking the numbers to be equal in exact order*/
{
for ( int j = 0 ; j < 3 ; j ++ )
{
if ( randomnumberarray[j] == inputarray[i] )
++repition ;
}
}

但是使用上述条件,如果用户输入相同的数字 3 次或随机数字相同,它会变得奇怪。

任何帮助都会有所帮助,谢谢。

如果你讨厌if-else-if梯子,我对你的问题的快速回答如下。 @Rao Ubaid 的答案几乎是正确的,但我们必须像这个演示一样丢弃已经匹配的猜测值,以避免重复计算:

int calcScore(
const std::vector<std::size_t>& ans,
std::vector<std::size_t> guess)
{        
assert((ans.size() == 3) && (guess.size() == 3));
if((ans[0] == guess[0]) && (ans[1] == guess[1]) && (ans[2] == guess[2])) {
return 4;
}
auto score = 0;
for (const auto ans_i : ans)
{
for (auto it = guess.begin(); it != guess.cend(); ++it)
{
if (*it == ans_i)
{
score += 1;
guess.erase(it);
break;
}
}
}
return score;    
}

接下来要考虑的是编写测试和性能调整。

我找到了一种方法。 这是代码。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int check ( int a , int n[3] )
{
for ( int i = 0 ; i < 3 ; i++ )
{
if ( a == n[i] )
{
return 1 ;
}
}
return 0 ;
}
int main ()
{
//PRE-PROGRAM DECLARATIONS
int n[3] , a[3] , input , repition ;
repition = 0 ;
srand(time(NULL)) ;
n[0] = rand() % 10 ;
n[1] = rand() % 10 ;
n[2] = rand() % 10 ;
//TESTING STUFF GOES HERE
//cout << n[0] << n[1] << n[2] << endl ;
//OUTPUT, INPUT, and PROCESSING
cout << "Enter your Guess Here : " ;
cin >> input ;
a[0] = input / 100 ;
a[1] = ( input % 100 ) / 10 ;
a[2] = ( input % 10 ) ;

//CONDITIONS
if ( a[0] == n[0] && a[1] == n[1] && a[2] == n[2] )
{
repition = 4 ;
}
else
{
for ( int i = 0 ; i < 3 ; i++ )
{
repition = repition + check( n[i] , a ) ;
}
}
//OUTPUT
switch (repition)
{
case 4:
cout << "All digits correct - Exact Order!n" ;
break ;
case 3:
cout << "All digits correct - Different Order!n" ;
break ;
case 2:
cout << "Two digits correct!n" ;
break ;
case 1:
cout << "Only One digit Correct!n" ;
break ;
case 0:
cout << "Sorry Try Again!n" ;
break ;
default :
cout << "Something is terrible!n" ;
}
return 0;
}