任务是在数组中搜索平方数并打印每两个平方数的总和。例如数组以 1 开头,以 9 结尾。首先,应该在数组中找到正方形。在这种情况下 - 1 , 4 , 9 。每个的总和将是 1+4= 5 , 1+9 = 10 , 4+9 = 13。在我的程序中,当我输入起始值 1 和结束值 9 时,它只会打印从 1 到 9 的数组。不知道问题出在哪里。
#include <iostream>
#include <math.h>
using namespace std;
int arr[10][4];
bool sqrsum(int); //prototype
int main (){
int n,m,j,a,b,x,y,finalpoint;
bool noresult;
cout << "Enter array starting value: " << endl;
cin >> n;
cout << "Enter array ending value: " << endl;
cin >> m;
if ((n<0)|| (m<0))
{
cout << "Values cannot be negative." << endl;
}
if (n>m)
{
j=n;
n=m;
m=j;
}
for (int i=n; i<=m; i++)
{
if (sqrsum(i) == true)
{
for (int g=0; g<10; g++)
if (arr[g][0] == -9)
{
finalpoint = g;
break;
}
}
if (finalpoint == 1)
{
cout << i << endl;
}
else
{
for (int g=0; g < (finalpoint / 2); g++)
{
cout << i << endl;
}
}
noresult = false;
}
if (noresult == true)
{
cout << "There is no valid square sum." << endl;
}
}
bool sqrsum(int i)
{
int arr1[101];
int x; // Last address
int z = 0;
bool rettrue = false;
//Function finding squares and their sum.
for (int j=0;j<10;j++)
{
for (int k=0;k<4;k++)
{
arr[j][k] = -9;
}
}
//Finding possible squares
for (int j=0; pow(j,2)<=i; j++)
{
arr1[j] = pow(j,2);
x = j;
}
//Cycles of sum
for (int j=0; j<=x; j++)
{
for (int k=0; k<=x; k++)
{
if (arr1[j] + arr1[k] == i)
{
arr[z][0] = arr1[j];
arr[z][1] = arr1[k];
arr[z][2] = j;
arr[z][3] = k;
z++;
rettrue=true;
}
}
}
if (rettrue == true)
return true;
else
return false;
}