【问题标题】:find all four digit numbers for which the square of the sum of the first two digits and the last two digits equal the number itself [closed]找到前两位数字和后两位数字之和的平方等于数字本身的所有四位数字[关闭]
【发布时间】:2020-01-25 01:54:48
【问题描述】:

我的代码应该执行所有 4 位数字,前两位数字和最后两位数字之和的平方应该等于它自己的数字,但我的它什么也不做。我做错了什么?

for (int i = 1000; i <= 9999; i++){
    int n = i;
    int remandier1, remandier2,finalanswer;
    double result1=0;
    while(n != 0){
        remandier1 = n % 100;
        remandier2 = n /100;
        finalanswer = remandier1 + remandier2;
        result1 = Math.pow(finalanswer, 2);
    }
    if (result1 == n){
        System.out.println(i);
    }
}

【问题讨论】:

  • 它不工作?请说明它应该做什么,以及它做错了什么。
  • 我编辑了这个问题,但简单地说,这个程序应该找到所有 4 位数字,其中第一个和最后两个数字的总和的平方等于它自己的数字。例如 3025. (30+25)^2 = 3025
  • 从标题看来,如果你有一个 abcd 形式的数字,那么你的条件应该是 (a+b)*(a+b)=(d+e)*(d+ e)=abde。 Sqrt(1000)=31.1 和 Sqrt(9999)=99.9。所以可能大于两位数的总和。所以可能你想要 (ab+de)^2=abce,循环 "while(n != 0)" 永远不会完成,因为你的 n 是 ==i,它在 1000 .. 9999 的范围内
  • 是的,我的意思是 (ab+cd)^2 = abcd。
  • 删除 "while(n != 0){ " 和相应的右大括号。避免将双打与等号进行比较。您可能会得到意想不到的结果。

标签: java math conditional-statements


【解决方案1】:

您正在使用基于n 不同于0 的循环,但n 在循环期间永远不会被修改。循环如何真正停止..循环?可能是我遗漏了一些东西,但在我看来,n 将永远等于 i 的设置值。

while(n != 0)
{
    remandier1 = n % 100;
    remandier2 = n /100;
    finalanswer = remandier1 + remandier2;
    result1 = Math.pow(finalanswer, 2);
    // add something to stop the loop
    n = n - 1; // for example
}

【讨论】:

  • 当我达到 9999 时,程序应该停止
  • i 永远不会达到 9999,因为它被困在 while 循环中,因此实际上只完成了一次 for 循环的迭代 - 而不是完全完成。您需要让while (n != 0) 在某一点停止。
猜你喜欢
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多