这个特定的代码块在我的函数中做了什么?
What is this certain block of code doing within my function?
这是整个代码。它采用整数 x 和 returns 整数 x 中最常见的数字,在平局的情况下也是 returns 较大的值。
#include <iostream>
using namespace std;
int max_frequency(int x)
{
int a[] = {0,0,0,0,0,0,0,0,0,0};
int temp, max;
while(x > 0)
{
temp = x%10;
x=x/10;
a[temp]++;
}
max = 0;
for(int i = 1; i < 10; i++)
{
if(a[i] >= a[max])
{
max = i;
}
}
return max;
}
int main()
{
int x;
cout << "Enter the integer: "<< endl;
cin >> x;
cout << max_frequency(x) << endl;
return 0;
}
我感到困惑的部分:
int max_frequency(int x)
{
int a[] = {0,0,0,0,0,0,0,0,0,0};
int temp, max;
while(x > 0)
{
temp = x%10;
x=x/10;
a[temp]++;
}
max = 0;
我知道 0 的数组用作计数器,我不明白的是分配给变量 temp 的是什么,以及为什么。我在编写这段代码时得到了一些帮助,但并没有向我清楚地解释这里发生了什么。如果有人不介意解释这篇文章,我将不胜感激。谢谢。
%
是模运算符,意思是x%y
等于x除以y的余数。在那种情况下,我们可以看到 x%10
returns 是 x 最右边的数字,对吗?现在我们可以计算数字的位数
这是整个代码。它采用整数 x 和 returns 整数 x 中最常见的数字,在平局的情况下也是 returns 较大的值。
#include <iostream>
using namespace std;
int max_frequency(int x)
{
int a[] = {0,0,0,0,0,0,0,0,0,0};
int temp, max;
while(x > 0)
{
temp = x%10;
x=x/10;
a[temp]++;
}
max = 0;
for(int i = 1; i < 10; i++)
{
if(a[i] >= a[max])
{
max = i;
}
}
return max;
}
int main()
{
int x;
cout << "Enter the integer: "<< endl;
cin >> x;
cout << max_frequency(x) << endl;
return 0;
}
我感到困惑的部分:
int max_frequency(int x)
{
int a[] = {0,0,0,0,0,0,0,0,0,0};
int temp, max;
while(x > 0)
{
temp = x%10;
x=x/10;
a[temp]++;
}
max = 0;
我知道 0 的数组用作计数器,我不明白的是分配给变量 temp 的是什么,以及为什么。我在编写这段代码时得到了一些帮助,但并没有向我清楚地解释这里发生了什么。如果有人不介意解释这篇文章,我将不胜感激。谢谢。
%
是模运算符,意思是x%y
等于x除以y的余数。在那种情况下,我们可以看到 x%10
returns 是 x 最右边的数字,对吗?现在我们可以计算数字的位数