数字程序错误的总和

时间:2014-01-30 00:55:27

标签: java sum-of-digits

我一直在研究一个程序来取整数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));
             }      
         }
    }
}

1 个答案:

答案 0 :(得分:1)

您将获得/ by zero个例外因为您的号码存储为整数,这意味着您通常会获得一个十进制值&lt; 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;