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

整数存储异常及输入字符误判为强数的C程序问题排查

Let's walk through the problems in your code and fix them step by step to resolve both the input storage issue and the incorrect strong number detection:

1. Uninitialized Variables Causing Chaos

The biggest culprit here is uninitialized local variables in your strong function:

  • Variables like r, n, and fact are declared but never assigned an initial value. In C, local variables hold garbage values by default, so operations like r = r % 10 or fact = fact * i will produce completely unpredictable results.
  • You’re using n = n / 10 but never set n to the input number—this variable is totally unused in your logic; you should be working with a copy of the input value instead.

2. Type Mismatches & Unhandled Input Failures

  • Your struct uses a long int for the number, but the strong function accepts an int. This creates an implicit type conversion that can truncate large numbers, and even break input storage in edge cases.
  • When you input non-numeric characters, scanf fails to read a value and leaves your struct’s a member with the garbage value from the uninitialized malloc’d memory. Your code then proceeds to compare this random value with the broken sum from strong, leading to false "strong number" results.

3. Broken Factorial Calculation

Your factorial loop starts at i=0, which immediately sets fact to 0 (since multiplying by 0 wipes out all previous values). Factorials should start at 1 and multiply up to the digit value.


Fixed Code

Here’s the corrected version with explanations of key fixes:

/* C program to find strong number using Structure and Pointers*/
#include<stdio.h>
#include<stdlib.h>

struct strg { long int a; }*strgvar;

// Match parameter/return type to struct's long int to avoid truncation
long int strong(long int num);

int main() {
    long int result;
    int input_status;

    // Allocate memory and check for allocation failure
    strgvar = (struct strg*) malloc(sizeof(struct strg));
    if(strgvar == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
    // Initialize struct member to avoid garbage values
    strgvar->a = 0;

    printf("Enter the number ...\n");
    // Check scanf's return value to verify successful input
    input_status = scanf("%ld", &strgvar->a);
    if(input_status != 1) {
        printf("Invalid input! Please enter a valid integer.\n");
        free(strgvar); // Clean up allocated memory before exiting
        return 1;
    }

    result = strong(strgvar->a);
    if(result == strgvar->a) {
        printf("Its a strong number !\n");
    } else {
        printf("Its not a strong number !\n");
    }

    free(strgvar); // Release allocated memory to prevent leaks
    return 0;
}

long int strong (long int num) {
    long int sum = 0;
    long int temp = num; // Use a temp variable to preserve original input

    while(temp != 0) {
        int digit = temp % 10; // Initialize digit with the current last digit
        long int factorial = 1; // Start factorial at 1 (correct base case)
        
        // Calculate factorial correctly from 1 to the digit value
        for(int i = 1; i <= digit; i++) {
            factorial *= i;
        }

        sum += factorial;
        temp /= 10; // Remove the last digit from temp
    }
    return sum;
}

Key Fixes Explained:

  • Proper Variable Initialization: All local variables and the malloc’d struct member are initialized to avoid garbage values.
  • Type Consistency: The strong function now uses long int to match the struct’s data type, preventing truncation.
  • Input Validation: We check scanf’s return value to catch invalid inputs (like characters) and exit gracefully instead of proceeding with bad data.
  • Correct Factorial Logic: The factorial loop starts at 1, so it calculates the correct product for each digit.
  • Memory Management: Added checks for malloc failure and explicit memory cleanup to avoid leaks.

内容的提问来源于stack exchange,提问作者Krishna Kumar S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:37:56