我正在做一個學校作業,並且無法弄清楚如何創建一個函數來計算在一個序列中打印多少個數字。我之前有過它的工作方式(如下所示),但計數函數需要是它自己的:如何創建一個計數函數來計算另一個函數序列中的數字量?
7.編寫一個函數的契約,然後是一個實現,函數接受一個整數n並返回冰雹序列的長度從n開始。這個功能不能寫(打印)任何東西。
將您的主要功能修改爲顯示冰雹序列和從n開始的冰雹序列的長度。
我對C++還比較陌生,而且我仍然在學習如何去做大部分工作。對不起,如果這是一個愚蠢的事情要求幫助。
// This program takes a user defined number 'n'
// and runs it through a function that returns
// the number that follows 'n' in hailstone sequence.
// Since there is no number that follows 1 in the sequence,
// this fuction requires its parameter 'n' to be greater
// than 1.
/*
What number shall I start with? 7
The hailstone sequence starting at 7 is:
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
The length of the sequence is 17.
The largest number in the sequence is 52.
The longest hailstone sequence starting with a number up to 7 has length 17
The longest hailstone sequence starting with a number up to 7 begins with 7
*/
#include <algorithm>
#include <cstdio>
using namespace std;
void hailstoneSequence(int n);
int main(int argc, char** argv)
{
int n;
printf("What number shall I start with? ");
scanf("%d", &n);
printf("The hailtone sequence starting at %d is: \n", n);
hailstoneSequence(n);
return 0;
}
// In hailstoneSequence, while 'n' is not equal to 1
// the function will calculate whether 'n' is even
// to computer n/2, otherwise it will compute 3n + 1 if 'n' is odd.
void hailstoneSequence(int n)
{
// hailLength will keep track of how many
// numbers are produced in the sequence.
int hailLength = 1;
printf("%i", n);
printf(" ");
while(n != 1)
{
if(n % 2 == 0)
{
n /= 2;
printf("%i", n);
printf(" ");
}
else
{
n = (3 * n) + 1;
printf("%i", n);
printf(" ");
}
hailLength++;
}
printf("\n");
printf("The length of the sequence is %i.", hailLength);
printf("\n");
}
這是我試圖去計算hailstoneSequence被使用的次數的其他函數。
int hailstoneLength(int hailLength)
{
hailLength++;
return hailLength;
}
這是我的主要功能部分tryign當與計數功能的工作:
int main(int argc, char** argv)
{
int n;
int hailLength = 0;
這是hailstoneSequence功能後:
while(n != 1)
{
if(n % 2 == 0)
{
n /= 2;
printf("%i", n);
printf(" ");
}
else
{
n = (3 * n) + 1;
printf("%i", n);
printf(" ");
}
hailstoneLength(hailLength);
//hailLength++;
}
我敢肯定,我現在打破它了。任何人都可以告訴我我做錯了什麼,或者幫助我理解如何讓函數計數?我仍然試圖谷歌如何調用函數中的函數和東西來嘗試這些方法。
如果沒有while循環的語句會更容易嗎? 我無法在此作業中使用遞歸。
我敢肯定,你只需要創建一個產生冰雹序列的大小_another_功能刪除hailLength的聲明和NBL。這兩個函數看起來很相似,但是其中一個輸出輸出,另一個計數迭代。 –
謝謝,我如何讓它知道我想讓函數計算它循環的迭代次數?我不是很瞭解它。 – Zabe