简体   繁体   English

直接数学C ++

[英]DIscrete Math C++

x^2 + y^2 = Z^2. x ^ 2 + y ^ 2 = Z ^ 2。 How to test the truth of Pythagoras Theorem in code? 如何用代码测试毕达哥拉斯定理的真相? My assignment says to read in 10 integers and test if the statement is true or false with each of the ten integers. 我的作业说要读10个整数,并用这10个整数中的每一个测试该语句是对还是错。 This is what I have but I'm not sure if its right because I'm not sure if I'm solving for z. 这就是我所拥有的,但是我不确定它是否正确,因为我不确定是否要求解z。

Any help appreciated 任何帮助表示赞赏

void ESearch(int array[], int size)
{
int trueCount = 0;
//int falseCount = 0;

for(int i = 0; i < size; ++i)
{
    for(int j = 0; j < size; ++j)
    {

        int x = array[i];
        int y = array[j];

        int z = sqrt(pow(x, 2)+ pow(y, 2));

        if(z == x || y)
        {
            ++trueCount;
        }

    }


}
if(trueCount > 0) cout << "\nE is TRUE"; else cout << "\nE is FALSE";

 }

Your code won't work the way you want. 您的代码无法按您想要的方式工作。 Try this. 尝试这个。 You have very small data size, so most probably you don't care much about efficiency, but I wrote some simple (not yet the most efficient) solution using STL. 您的数据量很小,因此很可能您不太在乎效率,但是我使用STL编写了一些简单(但不是最有效)的解决方案。 You define a vector and sort it once in order then to use binary search when you want to check whether the pair (x,y) satisfies Pyth. 您定义一个向量并对其进行一次排序,以便在要检查对(x,y)满足Pyth时使用二进制搜索。 theorem for some other integer from your input data. 输入数据中其他一些整数的定理。 It takes log(size) , so it should be reasonably fast even for large data inputs. 它需要log(size) ,因此即使对于大数据输入也应该相当快。 Also you don't need to run second loop from the beginning of the data, since you'll be already checking the same pair but in different order before. 同样,您也不需要从数据的开头运行第二个循环,因为您已经在检查同一对,但是之前的顺序不同。 The code should fairly simple, but if you have any questions, please ask. 代码应该相当简单,但是如果您有任何疑问,请询问。 Good luck. 祝好运。

void ESearch(int array[], int size)
{

int trueCount = 0;
std::vector<int> z(array, array + size);
std::sort(z.begin(), z.end());

int x, y;
double z_check;

for(int i = 0; i < size; i++)
{
    x = array[i];

    for(int j = i+1; j < size; j++)
    {
        y = array[j];

        z_check = sqrt(x*x + y*y);

        if(std::binary_search(z.begin(), z.end(), z_check))
        {
            trueCount++;
        }

    }
}
z.clear();
if(trueCount > 0) cout << trueCount; else cout << "\nE is FALSE";
}

EDIT: You can even speed up things a bit more since you know that you are looking for the number greater than sqrt(x*x+y*y) in sorted vector: 编辑:您甚至可以进一步加快处理速度,因为您知道在排序向量中查找的数字大于sqrt(x*x+y*y)

if(std::binary_search(z.begin() + ceil(z_check), z.end(), z_check))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM