这是我的shell:
import java.util.*;
//this example demonstrates how to to use a
//while loop to average all of the digits of a number
public class AveragingDigits
{
public static int countDigits( int num )
{
return 0;
}
public static double sumDigits( int num )
{
return 0.0;
}
public static double averageDigits( int num )
{
return 0.0;
}
public static void main(String args[])
{
Scanner kb = new Scanner( System.in );
System.out.print( "Enter a number :: " );
int num = kb.nextInt();
System.out.println("The digit average is " + averageDigits( num) );
}
}
我如何使用此shell打印使用扫描仪输入的数字的平均数字?
答案 0 :(得分:1)
你需要像这样做你的方法
public static int countDigits( int num )
{
return (String.valueOf(num)).length();
}
public static double sumDigits( int num )
{
double sum=0.0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static double averageDigits( int num )
{
return sumDigits(num) / countDigits(num);
}
答案 1 :(得分:1)
我试着用你的设置来做,但只用一个Calculate Average方法就可以更简单了。
public class AveragingDigits
{
int count=0;
int sum=0;
double temp=0;
double average=0;
double total=0;
public static int countDigits( int num )
{
if (num==num)
{
count++;
}
return count;
}
public static double sumDigits( double num )
{
temp=num;
total=total+temp;
return total;
}
public static double averageDigits( double num )
{
total=sumDigits( num );
count=countDigits( num );
return total/count;
}
public static void main(String args[])
{
Scanner kb = new Scanner( System.in );
System.out.print( "Enter a number :: " );
int num = kb.nextInt();
System.out.println("The digit average is " + averageDigits( num) );
}
}
答案 2 :(得分:0)
public class Test {
static String s = "";
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter a number :: ");
int num = kb.nextInt();
System.out.println("The digit average is " + averageDigits(num, 0, 0));
}
static double averageDigits(int number, int sum, int count) {
if (number == 0) {
if (count == 0) {
return 0;
}
return ((double) sum) / ((double) count);
} else {
return averageDigits(number / 10, sum + number % 10, ++count);
}
}
<强>输出强>
Enter a number :: 12345
The digit average is 3.0