计算数字根,还有更好的方法吗? [英] Calculating Digital Root, is there a better way?
本文介绍了计算数字根,还有更好的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我计算整数的数字根的方式.
This is how i calculated the digital root of an integer.
import acm.program.*;
public class Problem7 extends ConsoleProgram
{
public void run()
{
println("This program calculates the digital root of an interger.");
int num = readInt("Enter the number: ");
int sum = 0;
while (true)
{
if (num > 0)
{
int dsum = num % 10;
num /= 10;
sum += dsum;
}
else if (sum > 9)
{
int dsum = sum % 10;
sum /= 10;
sum += dsum;
} else if (sum <= 9 ) break;
}
println("Digital Root is: " + sum);
}
程序运行正常.
The program works fine.
是否有更好/更短的方法来计算数字的数字根. ?
Is there a better/shorter way of calculating the digital root of a number. ?
编辑/添加:这是通过使用泰勒的答案来实现上述问题的,它也可以正常工作:
EDIT/ADDED : Here is the implementation of the above problem by using Tyler's answer, it works as well:
import acm.program.*;
public class Problem7 extends ConsoleProgram
{
public void run()
{
println("This program calculates the digital root of an interger.");
int num = readInt("Enter the number: ");
println("Digital Root of " + num + " is: " + (1 + (num - 1) % 9));
}
}
推荐答案
#include <stdio.h>
int main(void)
{
int number;
scanf("%d", &number);
printf("The digital root of %d is %d.", number, (1 + (number - 1) % 9));
}
如果无法找到Ramans的公式,这就是我编写该程序的方式...:
Had I not been able to find Ramans' formula this is how I would write this program...:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int c;
int number = 0;
while ((c = getchar()) != EOF)
{
if (isdigit(c))
number += (c - '0');
}
if (number <= 9)
{
printf("The digital root is %d\n", number);
}
else
{
printf("%d", number);
}
}
编译后,要运行此命令,基本上只需将它们链接在一起即可.我认为整数可能是最多需要的四个.
After compiling, to run this, basically you just chain these together. I believe four is the most you could possibly need for an integer.
$ echo 829382938 | ./digitalroot | ./digitalroot | ./digitalroot | ./digitalroot
这篇关于计算数字根,还有更好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文