本文介绍了找到数组中的3个重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 大家好,我正在尝试编写一个5个骰子卷的功能,它应该计算3个相同数字出现的次数,例如。 (5,5,3,1,5) 在此之前,我已经有了一对有效的功能。但是我为threeSameNo编写的以下函数,它似乎也适用于对(4,2,4,1,2)或者有时,它确实可以在确实有3个相同数字的情况下工作,并且当它重新运行时它不起作用 - 即使有3个相同的号码也要运行程序。 我在某处做错了吗? 仅供参考,getValue是我为获取存储在数组中的每个骰子的值而编写的函数。 我尝试了什么: void DiceRoll :: threeSameNo() { int counter = 0 ; for ( int i = 0 ; i< 5 ; i ++) { for ( int j = i + 1 ; j< 5 ; j ++) { for ( int k = j + 1 ; k< 5 ; k ++) { if (dArray [i] .getValue()== dArray [j] .getValue()== dArray [k] .getValue()) { counter ++; cout<< 三种类型出现<< ENDL; } } } } } 解决方案 简单:停止查看数字! 将数据复制到第二个数组中。 对其进行排序。 查看,比较每个数字与前两个... 排序是内置的,效率很高,之后是单次检查以找到重复。 或者,因为您只有6个数字可供使用:设置第二个六个整数数组 - 称之为计数数组。将新阵列归零。循环遍历骰子滚动数组,并为每个滚动值增加计数数组中的相应索引。 之后快速通过数组数组会告诉您每个值已滚动多少次。 Quote: if(dArray [i] .getValue()== dArray [j] .getValue( )== dArray [k] .getValue()) 上面的行是有缺陷的(因为 == 评估为 0 或 1 )。 它应该是 (dArray [i] .getValue()== dArray [j] .getValue()&& dArray [j] .getValue()== dArray [k] .getValue()) 尝试,例如 cout<< ( 5 == 5 )<< ENDL; cout<< ( 5 == 5 == 5 )<< ENDL; Hi all, I am trying to write a function of 5 dice rolls where it should count the number of times whether 3 same numbers appear eg. (5,5,3,1,5)Before that, I already have a function for pairs which works. But the following function which I wrote for threeSameNo, it seems to work for pairs too (4,2,4,1,2) or sometimes, it does works where there is indeed 3 same numbers, and times it did not work when re-running the program even if there are 3 same numbers.Am I doing wrong somewhere?FYI, getValue is a function I wrote for getting the value of each dice that is stores within an array.What I have tried:void DiceRoll::threeSameNo(){ int counter = 0; for(int i = 0 ; i < 5 ; i++) { for(int j = i + 1 ; j < 5 ; j++) { for(int k = j + 1 ; k < 5 ; k++) { if (dArray[i].getValue() == dArray[j].getValue() == dArray[k].getValue()) { counter++; cout << "Three of A Kind appear " << endl; } } } }} 解决方案 Simple: stop looking at the numbers!Copy the data into a second array.Sort it.Look through, comparing each number with the previous two...Sorting is built in and pretty efficient, and after that it's a single pass check to find the repeats.Alternatively, since you only have 6 numbers to work from: set up a second array of six integers - call it the counts array. Zero the new array. Loop through the dice rolls array, and increment the appropriate index in the counts array for each roll value.A quick pass through the counts array afterwards tells you how many times each value has been rolled.Quote:if (dArray[i].getValue() == dArray[j].getValue() == dArray[k].getValue())The above line is flawed (because == either evaluates to 0 or 1).It should be(dArray[i].getValue() == dArray[j].getValue() && dArray[j].getValue() == dArray[k].getValue())Try, for instancecout << (5 == 5) << endl;cout << (5 == 5 == 5) << endl; 这篇关于找到数组中的3个重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-16 07:20