21xrx.com
2024-11-25 05:06:59 Monday
登录
文章检索 我的文章 写文章
C++程序:输出1000以内的水仙花数
2023-07-07 07:23:59 深夜i     --     --
C++ 输出 水仙花数 1000 以内

C++ is a widely used programming language for developing computer applications. One of the interesting problems that can be solved using C++ programming is finding the Narcissistic Numbers in the range of 1 to 1000.

Narcissistic Numbers, also known as Armstrong Numbers, are numbers that are equal to the sum of their digits raised to the power of the total number of digits in the number. For example, the number 371 is a Narcissistic Number because 3^3 + 7^3 + 1^3 = 371.

To find the Narcissistic Numbers in the range of 1 to 1000 using C++, we need to write a program that will iterate through all the numbers in this range and check if the number is Narcissistic or not. Here is a sample code that will do this:

#include

#include

using namespace std;

int main(){

  for(int i=1;i<=1000;i++){

   int num=i;

   int sum=0;

   int power=(to_string(i)).length();

   while(num>0){

     int digit=num%10;

     sum+=pow(digit,power);

     num/=10;

   }

   if(sum==i)

     cout<<<" ";

  }

  return 0;

}

The program above uses a for-loop to iterate through all the numbers in the range of 1 to 1000. It then extracts the individual digits of each number and raises them to the power of the total number of digits in the number. If the sum of the powered digits is equal to the original number, then it is a Narcissistic Number and is printed to the console.

Running this program will output all the Narcissistic Numbers in the range of 1 to 1000. These numbers include 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, and 407.

In conclusion, finding Narcissistic Numbers in the range of 1 to 1000 using C++ programming is an interesting and useful problem that can be solved in a few lines of code. This problem is a good example of how programming can be used to solve mathematical problems quickly and accurately.

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复