我的三角三元组程序有一个问题
There is an issue with my triangle triples program
我的程序应该列出1-500之间的所有直角三角形三元组。它不应该重复相同的三角形。例如,3、4、5与4、3、5相同,并且只应显示第一个。我还应该在程序的末尾有一个计数器,显示找到了多少三角形。到目前为止,这就是我所拥有的。它当前未显示正确数量的三角形,计数器工作不正常。感谢
// Naming
int counter;
// For loops and nested for loops
{
// Makes sure side A starts at 1 and is less than 500
for (int a = 1; a <= 500; a++)
{
// Makes sure side B starts at 1 and is less than 500
for (int b = 1; b <= 500; b++)
{
// Makes sure side C starts at 1 and us kess than 500
for (int c = 1; c <= 500; c++)
{
// If A squared + B squared = C squared and C squared, A, and B -->
// are all less than or equal to 500 then display the answer
if ((a*a)+(b*b) == c*c & a & b <= 500) {
// This is my counter I cannot seem to get it to work properly
// More info about counter at bottom
counter++;
cout << a << ", " << b << ", " << c << endl;
}
}
}
}
}
cout << endl;
// Displaying counter
cout << counter << endl << endl ;
system("PAUSE");
return EXIT_SUCCESS;
}
下面的行不会达到您的预期:
// If A squared + B squared = C squared and C squared, A, and B -->
// are all less than or equal to 500 then display the answer
if ((a*a)+(b*b) == c*c & a & b <= 500) {
^^^^^^^^^^^^
将其转换为:
if ((a*a)+(b*b) == c*c && a <= 500 && b <= 500) {
ps:正如@Code Apprentice进一步评论的那样,a <= 500 && b <= 500
已经由for
-循环保证,因此可以简化为:
if ((a*a)+(b*b) == c*c) {
在创建三元组之前,强制对它们进行排序。斜边总是最后一条,最短的边总是第一条。(我们不需要担心(a,a,b),因为这样的积分组合是不存在的。
因此,对于解三重(a,b,c),应该总是真的,a<b<c、 a>0,b>0,c>0。
简单。:)
您很可能会对某些三元组进行两次计数。如果你检查你的输出,你肯定会看到"3,4,5"重复了6次。事实上,每个三元组将重复6次。这表明,一个快速的解决方案是将你的计数器除以6。
或者,您可以通过使用外部循环来定义内部循环的起点来确保不会重复任何三元组:
for (int a = 1; a <= 500; a++)
{
// Makes sure side B starts at 1 and is less than 500
for (int b = a + 1; b <= 500; b++)
{
// Makes sure side C starts at 1 and us kess than 500
for (int c = b + 1; c <= 500; c++)
p.s.此外,if
条件中的错误保证每个数字组合都被计数,因此输出为625000000
。一定要按照胡永涛的回答来解决这个问题。
计数器未初始化为0。你像三角形一样跳过的逻辑在哪里?
相关文章:
- 我有一个关于C++提升的问题:: asio 和 std :: 异步
- 从文件导入数据时遇到问题.我有一个没完没了的循环
- 我有一个关于标准::矢量<shared_ptr>的问题
- 我有一个关于我的战斗系统HP代码的问题
- 我有一个问题,创建了C 中阻塞队列的向量
- 我有一个关于将 std::array 传递到函数中的问题
- 在C++中,这个Eigen::张量的声明是安全的,还是有缺陷的?我应该为它提交一个问题吗
- lldb/gdb 有什么问题,忽略 OS X 中的第一个 sleep() 语句?
- 我有一个 c++ 代码,它在启动时崩溃,然后到达问题所在 main() 的执行
- 两个类相互包含,下一个代码有什么问题?
- 我的三角三元组程序有一个问题
- 如果我使用c++11功能编译一个文件,同时将其链接到一个没有c++11编译器选项编译的库,会有什么问题吗
- 在C++中有一个引用成员有什么问题?
- 为什么我有一个兼容版本问题使用libpng与Xcode
- 在这段代码中,我有一个警告:控制达到非void函数的结束[- return-type].我怎样才能解决这个问题
- 为什么这里有一个端序问题
- 返回一个右值——这段代码有什么问题?
- 轻松自如地学习OpenGL但有一个问题
- 我有一个问题,了解如何与队列工作
- std::fclose()有一个非常奇怪的问题