在C中为Collat​​z猜想打印起始号码

时间:2019-02-09 02:28:25

标签: c

我一直在从事这项学校作业,我们正在C中创建Collatz Conjecture。我已经完成了所有代码,剩下的唯一事情就是传递数字并同时打印数字我从逻辑中得到回报。我尝试在每次更改输入之前和之后使用printf(),但这对于每次迭代仅打印两次。以下是其工作方式的示例。我还将代码放在下面。

For example
如果我输入数字4。我应该回来4,2,1

Input Passed : ./hw1 4

Expected Output: 4 , 2, 1 Child ID is : 0 Child ID 1 is : 17488 Parent ID is 17487 Parent PID 1 is : 17488

Actual Output: , 2, 1 Child ID is : 0 Child ID 1 is : 17488 Parent ID is 17487 Parent PID 1 is : 17488

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {

  // this is the number the user passes in 
  int n;

  int pid;
  int my_status;
  pid_t my_pid, my_secondpid;
  my_pid = fork();

  if (argc == 1) {
    fprintf(stderr, "Usage: ./hw1 <starting value>\n");

    return -1;
  }

  n = atoi(argv[1]); //  n is the input starting value

  // Error checking

  if (n < 0 || n == 0) {
    printf("Number cannot be less than 0");
    return 1;

  }

  //pid_t my_pid = fork();

  if (my_pid < 0) {
    printf("Unsuccesfull in creating the child process");
    return 1;

  } else if (my_pid == 0) {

    my_secondpid = getpid();

    //pid_t my_child = getpid();

    while (n != 1) {
      //pid_t my_child = getpid();

      // if the number is even
      if (n % 2 == 0) {
        //printf("%d " , n);
        n = n / 2;
        printf(" , %d", n);
        // printf("\n child id is : %d", my_child);
        // printf(" \n parent : %d" , my_pid);
        //printf("\n parent id is : %d" , my_pid);

      }
      // if the number is odd
      else if (n % 2 != 0) {
        //printf("%d" , n);
        n = 3 * n + 1;
        printf(" ,  %d", n);
        //printf("\n child id is : %d", my_child); 
        // printf(" \n parent : %d" , my_pid);
        //printf("\n parent id is : %d" , my_pid);

      }
      //printf("%d \n", n);

    } // end of while
    printf("\n");
    printf("\nChild ID is : %d", my_pid);
    printf("\nChild ID 1 is : %d", my_secondpid);
    //printf("\nProcess ID : %d", pid); 
  } // end of else if

  else {
    wait(NULL);
    my_secondpid = getpid();
    //printf("\n The starting  pid is : %d \n" , my_pid);
    printf("\nParent ID is %d", my_secondpid);
    printf("\nParent PID 1 is : %d", my_pid);
    printf("\n");

  }
  return 0;
}

0 个答案:

没有答案