整数转带正负号字符数组的C语言代码问题排查求助
Let's walk through the bugs in your code that are causing the wonky behavior with negative numbers and missing digits, then fix them step by step.
Key Issues in the Original Code
Wrong Input Format Specifier:
You usedscanf("%c", &number)to read an integer, but%conly reads a single character (storing its ASCII value intonumber). For example, if you input-123, the first character is-(ASCII 45), sonumbergets set to 45—a positive number. That’s exactly why you’re seeing+instead of-for negative inputs. You need to use%dto read an integer properly.findLengthFails for Negative Numbers:
YourfindLengthfunction useswhile(number > 0), which won’t run at all ifnumberis negative. This returns0as the length, so the subsequent for loop that adds digits never executes—hence no digits show up in the output.Storing Digits as Numeric Values Instead of Characters:
When you donumberArray[j] = number % 10;, you’re storing the raw numeric value of the digit (e.g., 5 instead of the character'5'). These values correspond to non-printable ASCII characters, so they don’t appear as digits. You need to add'0'to convert the numeric digit to its corresponding ASCII character.No Handling for Negative Digits:
For negative numbers,number % 10will return a negative value (e.g.,-123 % 10is-3). Adding'0'to this will result in an invalid, unprintable character. You should work with the absolute value of the number when extracting digits.
Corrected Code
First, make sure you define MAX_LEN (e.g., #define MAX_LEN 20 at the top of your file) to avoid array overflow.
#include <stdio.h> #include <stdlib.h> // For abs() function #define MAX_LEN 20 int findLength(int number); int main() { int number = 0, i = 0; char numberArray[MAX_LEN] = {0}; int length = 0; int save = 0; int j = 0; printf("Enter num: "); scanf("%d", &number); // Use %d to read integer correctly // Set the sign character if(number >= 0) { numberArray[i] = '+'; } else { numberArray[i] = '-'; } save = number; // Calculate length using absolute value to handle negatives length = findLength(abs(number)); number = save; j = length; // Digits start at index 1, end at index length // Work with absolute value to get positive digits int absNum = abs(number); for(i = 1; i <= length; i++) { numberArray[j] = (absNum % 10) + '0'; // Convert digit to printable character absNum /= 10; j--; } printf("%s\n", numberArray); return 0; } int findLength(int number) { int length = 0; // Handle 0 as a special case (it has a length of 1) if(number == 0) { return 1; } while(number > 0) { number /= 10; length++; } return length; }
Quick Extra Notes
- I added handling for the number
0infindLength—without this, inputting0would only print+with no digit. - Using
abs()simplifies working with negative numbers, ensuring we always use positive values when calculating length and extracting digits. - The array is initialized to all zeros, which guarantees the string is null-terminated (required for
printf("%s", ...)to display correctly).
内容的提问来源于stack exchange,提问作者Roee Attias

