查找数组中两个数字的平方和

时间:2014-02-16 16:26:59

标签: c arrays

我的程序应该从用户那里取一个数字,并在数组中找到两个数字,使得它们的平方和等于用户输入的平方。但是,我在这方面遇到了麻烦,并且理解了我遇到的所有错误。

这是我目前的尝试:

#include <stdio.h>
int numberaa;
scanf("%d",&numberaa);
int main()
{
    int i,j;
    int array[9] = {2,-4,6,3,9,0,-1,-9};
    for (i = 0; i <= 8; i++)
        for (j = 0; j <= 8; J++0)
            firstone==i*i
            secondone==j*j
            if {
                firstone+secondone=numberaa;
                printf("The Numbers are %d and %d",j,i,numberaa);
                return 0
            };

2 个答案:

答案 0 :(得分:3)

更改

firstone+secondone=numberaa;  

numberaa = firstone + secondone;   

啊!你需要获得一本基本的C书。这次我正在为您发布正确的代码。希望你能学到一些东西。

#include <stdio.h>

int main()
{
    int i,j;
    int array[9] = {2,-4,6,3,9,0,-1,-9};
    int numberaa;
    scanf("%d",&numberaa);

    for (i = 0; i <= 8; i++){
        for (j = 0; j <= 8; J++0){
            firstone = i*i
            secondone = j*j
            if(numberaa == firstone + secondone)
                  printf("The Numbers are %d and %d",j,i,numberaa);
        }
    }
    return 0 
}

答案 1 :(得分:3)

您至少需要仔细阅读有关C和通过示例的书籍的介绍性章节。这意味着键入它们(不,不要复制和粘贴),编译它们,然后运行它们以了解是什么使它们起作用以及它们会破坏它们。

编写自己的代码时,请始终在启用警告的情况下进行编译,例如: gcc -Wall -o my_executable_name my_code.c,并注意编译器错误和警告中引用的行号。

我将在下面的代码中指出一些错误位置:

#include <stdio.h>
int numberaa;  // Currently you're declaring this as a global.  NO! not what you want.
scanf("%d",&numberaa); // This isn't going to happen out here.  NO! NO NO NO!

int main()  // Specify your parameters.  int main(void)
{
  int i,j;
  int array[9] = {2,-4,6,3,9,0,-1,-9};  // why specify an array of 9 but store just 8 elements??
  for (i = 0; i <= 8; i++) // These are the correct limits for array[9].
    for (j = 0; j <= 8; J++0)  // j and J are not the same.  What is J++0 ????!!  Also, read about "blocks" and try a for-loop example with more than one line.
        firstone==i*i  // WTF??  Have you even tried to compile this? 
        secondone==j*j // See line above.
        if {  // Likewise
            firstone+secondone=numberaa; // Likewise again.
    printf("The Numbers are %d and %d",j,i,numberaa);  // How many formatting flags does your first argument have, and how many are to be inserted?
    return 0 };  // again, have you tried to compile this?

简短版本:

  • 分号
  • 作业与平等
  • 变量范围
  • 阻止,支撑使用
  • if陈述的语法
  • 您也没有对用户输入进行平方。
  • 效率:您只需为每个firstone = i * i值计算一次i,因此请将其移至j循环之外。