【问题标题】:Checking whether number is Armstrong Number or not in C在C中检查数字是否是阿姆斯壮数
【发布时间】:2021-04-03 00:26:16
【问题描述】:

阿姆斯壮数是一个数字,等于其数字的立方和。例如,0、1、153、370、371 和 407 是 Armstrong 数字。

我用这种方式试过这个程序-

    // Program to check whether number is Armstrong number or not
#include<stdio.h>

    int main()


{
    int a,r,sum=0,temp;
    //accepting input from user
    printf("Enter a number to check whether it is Armstrong number: ");
    scanf("%d", &a);
    
    //condition for checking if sum of individual numbers cube is equal to number
  do
  {
      r = a % 10;
      sum += r*r*r;
      a = a/10;

  } while (a>0);
  
    
    //printing final result.
    if(temp == sum)
    {printf("It is Armstrong Number.");}
    else
    {
        printf("It is not Armstrong Number.");
    }
    return 0;
    
}

在这里,我总是得到不是阿姆斯壮数字的结果,所以我检查了互联网,他们使用临时变量来存储输入数字。为什么这是必要的? 添加临时变量如何使代码工作?还有什么其他错误? 这是有效的代码:-

// Program to check whether number is Armstrong number or not
#include<stdio.h>
int main()
{
    int a,r,sum=0,temp;
    //accepting input from user
    printf("Enter a number to check whether it is Armstrong number: ");
    scanf("%d", &a);
    temp = a;
    //condition for checking if sum of individual numbers cube is equal to number
  do
  {
      r = a % 10;
      sum += r*r*r;
      a = a/10;

  } while (a>0);
  
    
    //printing final result.
    if(temp == sum)
    {printf("It is Armstrong Number.");}
    else
    {
        printf("It is not Armstrong Number.");
    }
    return 0;
    
}

【问题讨论】:

  • temp 未经初始化就使用,并且在第一个代码中调用了 undefined behavior
  • a = a/10; 更改存储在变量a 中的值。由于您想将立方体的总和与原始数字进行比较,因此您需要将此数字保留在某个地方。这恰好是第二个代码 sn-p 中名为 temp 的变量。您也可能应该检查输入的数字是否为负数...

标签: c input output


【解决方案1】:

您在条件temp == sum 中使用了temp,但在此之前您没有为temp 分配任何内容。 temp 这里的值是不确定的,因为它是一个未初始化的非静态变量(具有自动存储持续时间)。使用这种不确定的值会调用未定义的行为

其他错误是缩进不一致,scanf() 的结果没有被检查。此外,在乘法和加法中缺少检查以避免溢出也可以算作错误。

【讨论】:

    【解决方案2】:
    1. int a,r,sum=0,temp;
      

      temp 未在第一个代码中初始化。

    2. 他们使用一个临时变量来存储输入数字。为什么需要这样做?

    原因: do-while 循环执行后,a 的值变为零。因此,您没有原始数字可与 sum 变量进行比较。所以,我们复制原始号码a

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2014-06-30
      • 1970-01-01
      • 2021-04-06
      • 2022-06-15
      相关资源
      最近更新 更多