0

我一直在研究一个程序来获取整数 x 并找到任何数字之和乘以 x 等于该数字的数字。我的代码适用于数字 2、3 和 4,但除此之外,无论我在做什么,都会返回各种错误。任何帮助将不胜感激。

我的代码:

package SumOfTheDigits;

public class Test
{
    public static void main(String[] args) throws java.lang.Exception
    {
         int a = 3;
         int x = 1;
         int solutions =  (9 - ((((10 * x) - (a * x))/(a - 1)) % 9))/(((10 * x) - 
                          (a * x))/(a - 1));

         for(int z = 1; z < solutions + 2; z++)
         {
             if((z * 10) + ((10 * z) - (a * z))/(a - 1) == a * (z + ((10 * z) - 
                   (a * z))/(a - 1)))
             {
                 System.out.println(z + "" + ((10 * z) - (a * z))/(a - 1));
             }      
         }
    }
}
4

1 回答 1

1

您会遇到/ by zero异常,因为您的数字存储为整数,这意味着当您通常会得到一个十进制值 < 1 时,您实际上会得到 0。从您的代码中获取这个示例

int a = 15;
int x = 1;
// with the bottom half of your equation
int solutions = ....other math.../(((10 * x) - (a * x))/(a - 1))

// (((10 * 1) - (15 * 1))/(15 - 1)) = (-5/14) - > converted to integer = 0

所以..

int solutions = ....other math.../0

并抛出错误。您应该做的是将所有的转换int为双精度,以允许正确评估方程。

double a = 10;
double x = 1;
double solutions = ....;

对操作顺序也有信心,去掉一些括号:),有这么多看的头疼

double temp = (10*x - a*x)/(a - 1);
double solutions = (9 - (temp % 9))/temp;
于 2014-01-30T01:15:28.227 回答