Hailstone序列程序C ++

时间:2019-02-04 20:24:48

标签: c++ loops

我正在开发一个程序,大部分时间我都无法使用它。我面临的唯一问题是,我的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: %d\n", lengthHailstone(n));
    printf("The largest number in the sequence is %d\n", largest(n));
    printf("The longest hailstone sequence starting with a number up to %d has a length %d\n", n, longest(n));
    printf("The longest hailstone sequence starting with a number up to %d begins with %d", n, biggestHailstone(n));
    return 0;
}

1 个答案:

答案 0 :(得分:0)

  

我面临的唯一问题是我的maximum()函数(   尝试使用扫描算法)返回完全荒谬   试图在给定冰雹中找到最大整数时的值   n的顺序...任何人都可以引导我朝正确的方向前进   解决这个错误?

主要调查方向:

您未能将冰雹序列捕获到阵列A中。