C语言实现考拉兹猜想时起始数字无法正常打印的问题
Hey there! I see the issue right away—your code never prints the initial starting number you pass in, which is why the output starts with a comma instead of 4 when you run ./hw1 4. Let's fix that and clean up the output format at the same time.
The Root Problem
Right now, your code only prints the new value of n after each calculation, but it never outputs the original starting number. That's why you get , 2, 1 instead of 4, 2, 1. Your earlier attempt to print n inside the loop caused duplicates because you were printing the old value before modifying it, then printing the new value afterward.
The Fix
We'll adjust the output logic to:
- Print the initial value of
nfirst, before entering the loop. - In the loop, only print the comma and the new value after calculating it—this avoids duplicates and fixes the leading comma.
Here's the modified code with key changes marked:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> // Added atoi requires this header! int main(int argc, char *argv[]) { int n; pid_t my_pid, my_secondpid; // Use pid_t consistently if (argc == 1) { fprintf(stderr, "Usage: ./hw1 <starting value>\n"); return -1; } n = atoi(argv[1]); // Error checking if (n <= 0) { printf("Number cannot be less than or equal to 0\n"); return 1; } my_pid = fork(); // Moved fork after input validation (better practice!) if (my_pid < 0) { printf("Unsuccessful in creating the child process\n"); return 1; } else if (my_pid == 0) { my_secondpid = getpid(); // Print the initial number FIRST printf("%d", n); while (n != 1) { if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } // Print comma + new number after calculation printf(" , %d", n); } printf("\n"); // Fix: my_pid is 0 in child process—use my_secondpid for child ID printf("Child ID is : %d\n", my_secondpid); printf("Child ID 1 is : %d\n", my_secondpid); } else { wait(NULL); my_secondpid = getpid(); printf("\nParent ID is %d\n", my_secondpid); printf("Parent PID 1 is : %d\n", my_pid); printf("\n"); } return 0; }
Additional Notes
- I added
#include <stdlib.h>becauseatoi()requires this header (your original code might have had implicit declaration warnings). - Moved the
fork()call after input validation—no need to create a child process if the input is invalid! - Fixed the child ID print: in the child process,
my_pidis always0(the return value offork()for the child), so we should usemy_secondpid(which is set togetpid()) to show the actual child process ID.
Test Output
When you run ./hw1 4, you'll now get:
4 , 2, 1 Child ID is : 17488 Child ID 1 is : 17488 Parent ID is 17487 Parent PID 1 is : 17488
That matches your expected output perfectly!
内容的提问来源于stack exchange,提问作者lets0code

