简体   繁体   中英

How do i fix my Hailstone Sequence Output?

The code is supposed to take 1 command line argument (an integer) and ouput the corresponding Hailstone sequence and it does this sucessfully. However instead of printing just the sequence my code prints the integer and then the sequence.

#include<stdio.h>
#include<stdlib.h>

int Hailstone(int num)

{
if(num % 2 == 0) {
return num /=2;
}
else {
return num = (3 * num) + 1;
}
}

int main (int argc, char *argv[])
{
int n = atoi(argv[1]);
while (n != 1)
   {
      printf("%d\n", n);
      n = Hailstone(n);
   }
   printf("%d\n", n);
   return(0);
}

If you don't want the initial number be printed, you should make your code print only numbers after processed.

Example:

int main (int argc, char *argv[])
{
   int n = atoi(argv[1]);
   do
   {
      n = Hailstone(n);
      printf("%d\n", n);
   }
   while (n != 1);
   return(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM