[英]How to properly compare two arrays stored in memory?
我正在嘗試構建一個應該與數組進行比較的函數,一個函數由其自身生成(彩票數字),第二個數組由用戶輸入提交並存儲。
這應該用來計算彩票和用戶輸入提交的數字之間的匹配數字。 如果它們匹配,則應顯示一條消息,告訴用戶他已經贏得了大獎等。
這應該是比較兩個數組的函數。 我假設是正確的(更清楚地說:該程序是比較兩個數組中的相應元素,並保留匹配的數字的計數)?
int compare(int user[], int lottery[]){
int matches = 0;
for (int i = 0; i < SIZE; i++) {
if (user[i] == lottery[i]) {
matches++;
}
}
return matches;
}
當它返回到應該告訴用戶是否成功的主要功能時,問題就來了。 這是我在main函數中創建的一小段代碼:
int matches = compare(user, lottery);
if (matches) {
cout << "Congratulations, you have won the big prize" << endl;
}
else {
cout << "Please, try again" << endl;
}
如果用戶中獎,應該顯示一條消息,並計算與彩票號碼匹配的用戶數字。
實際輸出是用戶輸入的數字。 希望我能解釋自己。
如果您需要幫助,並且需要更多信息,這是完整的代碼。 http://cpp.sh/8ivyc
在您的情況下,在同一索引中只有一次相同的值可以匹配,但是所有值必須相等
第一種可能性,對您的代碼進行最少的更改:
int compare(int user[], int lottery[]){
int matches = 0;
for (int i = 0; i < SIZE; i++) {
if (user[i] == lottery[i]) {
matches++;
}
}
return (matches == SIZE); /* <<< modified */
}
但是在發現另一個值之后繼續比較是沒有用的,因此可以是:
int compare(int user[], int lottery[]){
for (int i = 0; i < SIZE; i++) {
if (user[i] != lottery[i]) {
return 0;
}
}
return 1;
}
並且因為您使用的是C ++:
bool compare(int user[], int lottery[]){
for (int i = 0; i < SIZE; i++) {
if (user[i] != lottery[i]) {
return false;
}
}
return true;
}
(當然也將調用改為使用布爾值而不是整數 )
最簡單的方法是只使用std::array
。 如果使用std::array
,則可以使用==
進行比較!
函數populate
和show_values
可以這樣編寫:
void populate(std::array<int, SIZE>& nums) {
srand(time(0));
for (int& value : nums) {
value = rand() % 9;
}
}
void showValues(std::array<int, SIZE>& nums) {
for (int i = 0; i < SIZE; i++) {
cout << setw(3) << nums[i];
}
cout << endl;
}
並且compare
特別簡單:
bool compare(std::array<int, Size>& nums1, std::array<int, Size>& nums2) {
return nums1 == nums2;
}
檢查不平等而不是平等。 一旦用戶元素不等於彩票元素,您將退出該函數
int compare(int user[], int lottery[]){
for (size_t i = 0; i < SIZE; i++) {
if (user[i] != lottery[i]) {
return 0;
}
}
return 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.