毕达哥拉斯的三元组程序



我写了一个程序,它应该很简单,但在执行时,它没有给出想要的结果。即使在调试程序时,我想我也发现了错误(陷入了第一个if条件(,但我无法解决它(也许是我缺乏经验(。无论如何,这个本应节俭的项目花了3天时间,而我预计只需要几个小时。请帮我指导我哪里出了问题以及如何解决。这是代码

/*WAP to read pre entered no. of ints. consider only +ve and print the pythagorean triplets in them.*/
#include <stdio.h>
int main(){
int c,p,pp,count=0,a;
printf("How many entries to accept?n");
scanf("%d",&a);
printf("Enter the nos.n");
for (int i = 0; i < a; i++)
{
scanf("%d",&c);
if (c<0)    //skip -ve nos.
{       
continue;
}
if (count==0) 
{
pp=c;
count++;
}
else if (count==1)
{
p=c;
count++;
}
else if ((pp*pp)+(p*p)==(c*c))  //Tracking count not necesarry after first three
{
printf("Pythagorean triplet foundn");
printf("%d %d %d",pp,p,c);
pp=p;
p=c;
}
}

return 0;
}

主要目的是首先扫描一个编号,以表示要读取的输入。然后在一个循环中扫描由空格或回车分隔的输入,该循环将只接受前面所述的输入数量。它应该忽略任何-ve条目。如果它遇到勾股三元组,它应该以连续的方式打印出来,即三元组应该一个接一个地出现&不是随机的我们必须在不使用数组的情况下完成任务

示例输入是(您可以考虑任何((全部通过终端提供((条目数量(

6

1-1 3 4-4 5(这里它将忽略-1&-4(

预期输出将为

毕达哥拉斯三元组找到

3 4 5

我还在学习,很抱歉这个精心设计的程序。

提前谢谢。

由于我看不到输入文件,我不知道值是否排序,因为我们需要确定哪一个是斜边,这让它有点麻烦。

也不清楚"跳过底片"是什么意思。它是指吗

  • 我们可能看到3-6 4 5并说"是的,3,4,5"是一个三元组
  • 我们可能会看到3-4 5,然后说是的3 4 5
  • 或者我们可能会看到3-4 5,然后忽略整个集合

我假设了第一个

#include <stdio.h>
int main() {
printf("How many entries to accept?n");
int a;
if (scanf("%d", &a) != 1) {
printf("bad inputn");
return (-1);
}
printf("Enter the nos.n");
for (int i = 0; i < a; i++)
{
int sides[3] = { 0 };
int max = 0; // longest side length -> hypot

for (int j = 0; j < 3; j++)
{
int c;

if (scanf("%d", &c) != 1) {
printf("bad inputn");
return (-1);
}
if (c < 0)    //skip -ve nos.
j--; // try again
else {
if (c > max) {
max = c;
}
sides[j] = c;
}
}
int hyp = max * max; // hypotenuse squared
int adjTot = 0;      // adj sides squared total
for (int j = 0; j < 3; j++)
{
if (sides[j] == max)
continue;
adjTot += sides[j] * sides[j];
}
if (adjTot == hyp)
printf("%d %d %d is pyn", sides[0], sides[1], sides[2]);
else
printf("%d %d %d isnt pyn", sides[0], sides[1], sides[2]);

}
return 0;
}

既然你说你正在从一个文件中读取,如果有非数字数据,它就会退出

最新更新