冰雹序列程序的问题 C++.

Issue with Hailstone sequence program C++

本文关键字:问题 C++ 程序      更新时间:2023-10-16

我正在开发一个程序,大部分时间我都把它记下来了。我面临的唯一问题是我的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 中。