对于数字序列 a1, a2,...,an,我们说存在一个句点,如果1≤p 并且如果它成立,则对于该等式有意义的所有值来说,它是 ai=ai+p。
例如,数字序列 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 的周期为 5,因为 ai=ai+5 对于所有值,使得索引i 和i+5 都在允许范围内(即1 到7 包括在内)。同样的序列也有一个周期 10。接下来,如果至少存在一个数字作为该序列的周期,我们就说该数字序列是周期性的,最小的这样的数字称为基本序列周期。如果这样的数字不存在,则该序列不是周期性的。例如,上面的数字序列是周期的,基周期为5,而数字序列4,5,1,7,1,5不是周期的。
#include <iostream>
#include <vector>
int period(std::vector<double> vektor) {
int p;
for (int i : vektor) {
for (int j : vektor) {
if (vektor[i] == vektor[j])
p = j;
}
}
return p;
}
int main() {
std::vector<double> vektor{1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3};
std::cout << period(vektor);
return 0;
}
你能帮我修复这个代码吗?这将返回 3 作为序列的基期。
For a sequence of numbers a1, a2,...,an, we say that there is a period if 1≤p<n
and if it holds that it is ai=ai+p for all values for which this equality makes sense.
For example, the sequence of numbers 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 has period 5, because ai=ai+5 for all values such that both indices i and i+5 are within the allowable range (i.e. for 1 to 7 inclusive). The same sequence also has a period of 10. Next, we say that the sequence of numbers is periodic if it exists at least one number that is the period of that sequence, with the smallest such number being called the base sequence period. If such a number does not exist, the sequence is not periodic. For example, the above the sequence of numbers is periodic with the base period 5, while the sequence of numbers 4, 5, 1, 7, 1, 5 is not periodic.
#include <iostream>
#include <vector>
int period(std::vector<double> vektor) {
int p;
for (int i : vektor) {
for (int j : vektor) {
if (vektor[i] == vektor[j])
p = j;
}
}
return p;
}
int main() {
std::vector<double> vektor{1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3};
std::cout << period(vektor);
return 0;
}
- This should be solved using vector.
Could you help me fix this code? This returns 3 as base period of sequence.
发布评论
评论(1)
对于初学者来说,当所有初始化器都具有
int
类型时,不清楚为什么要使用值类型为double
的向量而不是int
类型。函数
period
应该接受一个常量引用的向量。变量
p
未初始化。因此,该函数可能返回不确定的值。基于范围的 for 循环不会像您想象的那样返回容器中的索引
它返回存储在 double 类型的向量对象中。
所以 if 语句中的条件
没有意义。
该函数可以如下所示,如下面的演示程序所示。
程序输出是
For starters it is unclear why you are using a vector with the value type
double
instead of the typeint
when all initializers have the typeint
.The function
period
should accept a vector by constant reference.The variable
p
is not initialized. As a result the function can return an indeterminate value.The range based for loop does not return indices in a container as you think
It returns stored in the vector objects of the type double.
So the condition in the if statement
makes no sense.
The function can look the following way as it is shown in the demonstration program below.
The program output is