冰雹序列程序的问题 C++.
Issue with Hailstone sequence program C++
我正在开发一个程序,大部分时间我都把它记下来了。我面临的唯一问题是我的largest()
函数(尝试使用扫描算法(在尝试查找给定冰雹序列 n 中的最大整数时返回完全荒谬的值。似乎对于我测试的前几个值,它们很好,比如 1 或 2,但如果我输入 3 或更高,我会得到类似 1153324768 的东西,这根本不是答案。有人能够引导我朝着正确的方向修复此错误吗?我在下面列出了我的代码
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
// Next(n) returns the number that follows n in a hailstone sequence.
// For example, next(7) = 22 and next(8) = 4.
//
// Next requires n > 1, since there is no number that follows 1.
int Next(int n)
{
int remainder;
remainder = n % 2;
if (n>1)
{
if(remainder == 0)
{
return n/2;
}
else
{
return 3 * n + 1;
}
}
else
{
return n;
}
}
// The function writeHailstoneSequence(n) will take the parameter n
// and write the entire hailstone sequence starting from n, all in one line.
void writeHailstoneSequence(int n)
{
printf("The hailstone sequence starting with %d is: %d ", n, n);
while (n > 1)
{
n = Next(n);
printf("%d ", n);
}
}
// The function lengthHailstone(n) will take the parameter n and return the
// the length of the hailstone sequence starting at n.
int lengthHailstone(int n)
{
int length = 1;
while (n > 1)
{
n = Next(n);
length++;
}
return length;
}
//The function largest(n) will take one parameter, integer n, and return the largest value.
int largest(int n)
{
int A[] = {};
int big = A[0];
for(int i = 0; i < n; i++)
{
big = max(big, A[i]);
}
return big;
}
// The function longest(n) will return the longest hailstone sequence starting witht a number from 1 to n.
int longest(int n)
{
int lon = 0;
for (int i = 1; i <= n; i++)
{
lon = lengthHailstone(n);
}
return lon;
}
// The function largestHailstone(n) returns the largest value that occurs in a hailstone sequence that starts
// with a number from 1 to n.
int biggestHailstone(int n)
{
int biggest = 0;
for (int i = 1; i <= n; i++)
{
biggest = largest(n);
}
return biggest;
}
int main()
{
int n;
printf("What number shall I start with?n");
scanf("%d", &n);
writeHailstoneSequence(n);
printf("nThe length of the sequence is: %dn", lengthHailstone(n));
printf("The largest number in the sequence is %dn", largest(n));
printf("The longest hailstone sequence starting with a number up to %d has a length %dn", n, longest(n));
printf("The longest hailstone sequence starting with a number up to %d begins with %d", n, biggestHailstone(n));
return 0;
}
我面临的唯一问题是我最大的((函数(这是 尝试使用扫描算法(返回完全荒谬 尝试在给定冰雹中查找最大整数时的值 n... 有人能引导我朝着正确的方向前进吗 修复此错误?
主要调查方向:
您未能将冰雹序列捕获到阵列 A 中。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题