以下是四平方和定理的C++代码实现:

#include <iostream>
#include <cmath>
using namespace std;

void printSquares(int n) {
    int max = sqrt(n / 4); // 计算最大平方数的上限
    for (int a = 0; a <= max; a++) {
        for (int b = a; b <= max; b++) {
            for (int c = b; c <= max; c++) {
                int d = sqrt(n - a*a - b*b - c*c); // 计算第四个数
                if (a*a + b*b + c*c + d*d == n) { // 如果符合条件,输出结果
                    cout << a << "^2 + " << b << "^2 + " << c << "^2 + " << d << "^2 = " << n << endl;
                }
            }
        }
    }
}

int main() {
    int n;
    cout << "请输入一个正整数:";
    cin >> n;
    cout << "四平方和定理的解为:" << endl;
    printSquares(n);
    return 0;
}

在这个程序中,我们定义了一个printSquares函数来输出所有符合四平方和定理的结果。我们使用三个循环来枚举前三个平方数的值,然后计算第四个数的值。如果四个数的平方和等于给定的数n,则输出结果。

main函数中,我们首先读入一个正整数n,然后调用printSquares函数来输出所有符合条件的结果

输出所有四平方和定理c++

原文地址: https://www.cveoy.top/t/topic/fDjF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录