比较C++变量的最有效方法
Most Efficient way to compare variables in C++
我有一个任务是为下面的问题制作代码。
编写一个彩票游戏应用程序,该应用程序将生成三个随机数,每个随机数介于 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;
}
相关文章:
- 在C++中初始化向量映射的最有效方法
- 将此布尔值传递给此函数的最有效方法是什么?
- 比较C++变量的最有效方法
- 在 c++ 中解决段树以外的范围查询的有效方法是什么?
- 存储变量的更有效方法是什么?
- 确保套装新鲜度的有效方法
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 在C++事务之间存储大量字符数据的有效方法
- 在unordered_multimap中精确迭代一次每个键的有效方法
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 检查两个向量是否并行的最有效方法
- 从浮点数中删除小数部分但保留类型的有效方法
- 传递非泛型函数的最有效方法是什么?
- 按升序打印矢量的所有元素直到它为空而没有重复项的最有效方法是什么?
- 创建字符串数组的有效方法
- 返回一个引用C++中另一个类对象的对象的有效方法
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 从std::map值中获取密钥的有效方法