You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

整数转带正负号字符数组的C语言代码问题排查求助

Fixing Your Integer-to-Character-Array Conversion Code

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 used scanf("%c", &number) to read an integer, but %c only reads a single character (storing its ASCII value into number). For example, if you input -123, the first character is - (ASCII 45), so number gets set to 45—a positive number. That’s exactly why you’re seeing + instead of - for negative inputs. You need to use %d to read an integer properly.

  • findLength Fails for Negative Numbers:
    Your findLength function uses while(number > 0), which won’t run at all if number is negative. This returns 0 as 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 do numberArray[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 % 10 will return a negative value (e.g., -123 % 10 is -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 0 in findLength—without this, inputting 0 would 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:42:34