java - 如何添加到累积字符串:
问题描述
在我的一个实验室中,我必须生成所有毕达哥拉斯三元组,直到达到特定的最大值。我发现了如何获取它们,但不知道如何将它们中的每一个添加到特定的字符串中。如何更改代码使输出看起来像这样?
3 4 5
5 12 13
7 24 25
8 15 17
9 40 41
11 60 61
12 35 37
13 84 85
代码:
private int greatestCommonFactor(int a, int b, int c)
{
int max = number;
for (a = 1; a <= max; a++)
{
for (b = a; b <= max; b++)
{
for (c = 1; c <= max; c++)
{
if (a * a + b * b == c * c)
{
}
else
{
continue;
}
}
}
}
return 1;
}
public String toString(){
String output = ;
return output+"\n";
}
解决方案
你不应该传递a,b,c
给方法,它们只是局部变量,但你可以传递max
. 然后你不需要迭代 for ,只需从和c
计算它a
b
private static void greatestCommonFactor(int max) {
for (int a = 1; a <= max; a++) {
for (int b = a; b <= max; b++) {
double c = Math.sqrt(a * a + b * b);
if (c == Math.floor(c)) {
System.out.println(a + " " + b + " " + (int) c);
}
}
}
}
调用为greatestCommonFactor(50);
您可以将条件更改if (c == Math.floor(c) && c < max)
为您喜欢的
推荐阅读
- intersystems-cache - 意外的 SQL 错误返回
在系统间缓存中 - javascript - How to make this regex accept decimals also
- javascript - 动画删除动态 Angular 组件?
- path - 从同一个父目录开始创建多个路径的推荐方法是什么?
- typescript - TypeScript - 使用 keyof 时验证与键关联的值是否正确
- java - Java 将自定义异常的消息添加到特定函数抛出异常的位置
- jsf - p:commandButton 在数据表中不起作用 - JSF
- javascript - 等待 setAttribute() 方法以执行另一个动作
- firebase - Firebase 规则中的当前年份
- ionic-framework - ionic devapp - 模块 card.io 不存在