早教吧 育儿知识 作业答案 考试题库 百科 知识分享

急!两道C++题1)PythagoreanTriples:Arighttrianglecanhavesidesthatareallintegers.AsetofthreeintegervaluesforthesidesofarighttriangleiscalledaPythagoreantriple.Thesethreesidesmustsatisfytherelationshipthatthes

题目详情
急!两道C++题
1) Pythagorean Triples: A right triangle can have sides that are all integers. A set of
three integer values for the sides of a right triangle is called a Pythagorean triple.
These three sides must satisfy the relationship that the sum of the squares of two of
the sides is equal to the square of the hypotenuse. Write a program that will print
all Pythagorean triples for side1, side2 and hypotenuse, all no longer than 500.
------------
Output (some of the triples produced are):
base height hyp
3 4 5
4 3 5
5 12 13
7 24 25
40 9 41
...
(Hint: You must check whether base^2 + height^2 is a perfect square.)
2) Write a program that accepts a valid input for the age of an employee in a company.
A valid age is in the range [21, 65] (i.e., >= 21 and <= 65).
If the user inputs an age that is not in the valid range, your program will inform
the user that the input is not valid, define the valid input, and prompt the user
once more.
-------------
Sample Test Data:
Enter age: 19
19 is not valid. A valid age is in the range [21, 65]. Try again !
Enter age: 70
19 is not valid. A valid age is in the range [21, 65]. Try again !
Enter age: 25
25 is valid. Thanks for using our validator !
▼优质解答
答案和解析
1>
#include
#include
using namespace std;
int main()
{
int b,h,hyp=0,t;
double r;
cout< for(b=3;b<=500;b++)
for(h=3;h<=500;h++)
{
t=b*b+h*h;
hyp=r=sqrt((double)t);
if(hyp>500)
continue;
if(hyp==r)
printf("%4d%7d%4d\n",b,h,hyp);
}
return 0;
}
2>
/*输入NULL结束*/
#include
int main()
{
int age;
while(scanf("%d",&age))
if(age>=21&&age<=65)
printf("%d is valid.Thanks for using our validator!\n",age);
else printf("%d is not valid.A valid age is in the range[21,65].Try again!\n",age);
return 0;
}