存储字符代替整数

标签 c struct scanf

存储字符代替整数

    /* C program to find strong number using Structure and Pointers*/

#include<stdio.h>
#include<stdlib.h>

struct strg {
    long int a;
}*strgvar;

int strong(int);

int main() {
    int result;
    strgvar = (struct strg*) malloc(sizeof(struct strg));
    printf("Enter the number ...\n");
    scanf("%ld", &strgvar -> a);
    result = strong(strgvar -> a);
    if(result == strgvar->a) {
        printf("Its a strong number !");
    }
    else {
        printf("Its not a strong number !");
    }
    return 0;
}   

int strong (int a) {
    int fact, r, n, sum = 0;
    while(a != 0) {
        r = r % 10;
        for(int i =0; i <= r; i++) {
            fact = fact * i;
        }
        sum = sum + fact;
        n = n/ 10;
    }
    return sum;
}
<小时/>

运行此程序时,输入的整数未存储在变量中。但是在输入任何字符时,它会打印“Its a Strong number!”

示例:

case 1:

Enter the number... 234

2

178

er

fg yu8 . case 2: Enter the number ...e

这是一个强大的数字!

最佳答案

除非a==0开始,否则strong中的循环显然是无限的。如果 scanf 失败,strgvar->a未初始化,因此您的程序具有未定义的行为。一种“合理”的可能性是该值被读取为 0,从而产生观察到的结果。

关于存储字符代替整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477181/

相关文章:

c++ - Exe 不能在旧版本的 Windows 上运行

将字符串数组复制到另一个字符串数组 - C

c - 如何正确定义和使用返回类型为用户定义结构的函数? (在 C 中)

c - Scanf 和 While 循环不等待用户输入

c - 为什么将 scanf() 的结果与 NULL 进行比较会生成编译器警告?

c - 陷入 C 词典项目

c - SPI(串行端口通信)问题,卡在 ioctl() 上

c - 为什么我的 fscanf() 不读取中间变量?

c++ - C++ 和 C 使用同一种链接器吗?

c - asn1c : Why do i need to free this member of this struct?