21xrx.com
2024-06-02 23:02:54 Sunday
登录
文章检索 我的文章 写文章
C++程序计算四位数各位数平方和
2023-07-13 19:17:38 深夜i     --     --
C++ 四位数 各位数 平方和 计算

C++是一种广泛使用的编程语言,可用于开发各种应用程序,包括计算机游戏,图像处理和科学计算。今天我们将学习如何使用C++编写一个程序来计算一个四位数各位数平方和的值。

首先,我们需要定义一个变量来存储四位数,我们可以使用整数类型的变量来存储这个数,例如:

int num = 1234;

接下来,我们需要把这个数的每一位分离出来,可以使用%运算符和/运算符来完成这个任务。%运算符用于获取余数,/运算符用于获取商。例如:

int thousand = num / 1000; // 获取千位上的数字

int hundred = (num / 100) % 10; // 获取百位上的数字

int ten = (num / 10) % 10; // 获取十位上的数字

int one = num % 10; // 获取个位上的数字

现在我们已经分离出了每一位数字,我们可以使用一个for循环来计算这个四位数各位数平方和的值。我们可以使用一个变量来存储总和,并在每一次循环中将每一位数字的平方加入到总和中,例如:

int sum = 0; // 定义总和变量

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

 int digit;

 if (i == 1)

  digit = thousand;

  else if (i == 2)

  digit = hundred;

  else if (i == 3)

  digit = ten;

  else

  digit = one;

 sum += digit * digit; // 将每一位数字的平方加入总和

}

最后,我们可以输出计算出的结果,例如:

cout << "四位数各位数平方和为:" << sum << endl;

这里是完整的程序代码:

#include

using namespace std;

int main() {

 int num = 1234;

 int thousand = num / 1000; // 获取千位上的数字

 int hundred = (num / 100) % 10; // 获取百位上的数字

 int ten = (num / 10) % 10; // 获取十位上的数字

 int one = num % 10; // 获取个位上的数字

 int sum = 0; // 定义总和变量

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

  int digit;

  if (i == 1)

   digit = thousand;

   else if (i == 2)

   digit = hundred;

   else if (i == 3)

   digit = ten;

   else

   digit = one;

  sum += digit * digit; // 将每一位数字的平方加入总和

 }

 cout << "四位数各位数平方和为:" << sum << endl;

 return 0;

}

通过这个程序,我们可以轻松地计算出任意四位数各位数平方和的值,使我们更好地掌握了C++编程的基本知识。

  
  

评论区

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