一道JAVA题目..急

2024-12-04 22:51:54
推荐回答(3个)
回答1:

楼上算法有点小错误,综合初始值是0开始,你的结果会比实际大1

package com.test;

/**
* 计算接口
* @author
*
*/
public interface OneToN {
public int jisuan(int n);
}

package com.test;

/**
* 1-N累加实现类
* @author acer
*
*/
public class Add implements OneToN {

public int jisuan(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}

}

package com.test;

/**
* 1-N阶乘实现类
* @author
*
*/
public class Mul implements OneToN {

public int jisuan(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum *= i;
}
return sum;
}

/**
* 测试方法
* @param args
*/
public static void main(String[] args) {
OneToN ot1= new Add();
OneToN ot2 = new Mul();
ot1.jisuan(3);
ot1.jisuan(5);
}
}

回答2:

挖。。这题真划算。。
interface OneToN
{
int jisuan(int n);
}
class A implements OneToN
{
public int jisuan(int n)
{
int m=0;
for(int i=1;i<=n;i++)
m+=i;
return m;
}
}
class B implements OneToN
{
public int jisuan(int n)
{
int m=1;
for(int i=1;i<=n;i++)
m*=i;
return m;
}
}
//以下为测试类
public class test
{
public static void main (String[] args) {
System.out.println (new A().jisuan(5));
System.out.println (new B().jisuan(5));
}

}

回答3:

package com.test;

/**
* 计算接口
* @author aotori
*
*/
public interface OneToN {
public int jisuan(int n);
}

package com.test;

/**
* 1-N累加实现类
* @author acer
*
*/
public class Add implements OneToN {

public int jisuan(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}

}

package com.test;

/**
* 1-N阶乘实现类
* @author
*
*/
public class Mul implements OneToN {

public int jisuan(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum *= i;
}
return sum;
}

/**
* 测试方法
* @param args
*/
public static void main(String[] args) {
OneToN ot1= new Add();
OneToN ot2 = new Mul();
ot1.jisuan(3);
ot1.jisuan(5);
}
}