我是C ++的新手。我试图读取数字数组并计算数组中与用户输入的数字相等的数字量。我不知道接下来要做什么让它使number = number1并计算它。我希望这是有道理的。感谢。
#include <iostream>
using namespace std;
int main()
{
int number[20] = {80, 52, 25, 71, 56, 90, 87, 10, 32, 80, 2, 67, 73, 50, 52, 73, 72, 20, 86, 99};
int numberCount = 0;
int number1 = 0;
cout << "Enter a number between 0 and 100: ";
cin >> number1;
while(number1>100 || number1<0)
{
cout << "Invalid number,enter again" << endl;
cin >> number1;
}
for(i = 0; i < 20; i = i + 1)
{
}
system("pause");
return 0;
}
答案 0 :(得分:4)
标准库中有一个函数,在<algorithm>
标题中:
int numberCount = std::count(number, number + 20, number1);
答案 1 :(得分:2)
您只需要测试number1
是否等于存储在数组中的每个值。使用变量i
作为索引(已在for循环中设置),您可以逐个访问数组的值并与number1
进行比较。如果它们匹配,则增加计数器变量。
for(i = 0; i < 20; i = i + 1)
{
// the next line tests whether the value of variable `number1` is equal
// to the value stored in the `number` array, at the index `i`
if(number1 == number[i])
{
numberCount += 1; // if there is a match, increment the counter
}
}
答案 2 :(得分:0)
将数组'number []'中的每个条目与用户'number1'提供的数字进行比较:
for (int i = 0; i < 20; i++)
{
if (number1 == number[i])
{
numberCount++;
}
}