//要求编写任意数n从键盘输入,以递归的方式计算1+2+3+...+n .
import java.io.*;
public class digui1
{
public static void main(String args[]) throws IOException
{
BufferedReader buf;
String str;
int n, m;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input your number:");
str=buf.readLine();
n=Integer.parseInt(str);
m=fac(n);
System.out.println("1+2+3+...+n="+m);
}
public static int fac(int n)
{
if(n==1)
return 1;
else
return (fac(n-1)+1);
}
}我的结果
E:\java>java digui1
Input your number:
10
1+2+3+...+n=10
(怎么上一行的结果会等于10呢?)谢谢各位好心的大哥哥帮我改改!
import java.io.*;
public class digui1
{
public static void main(String args[]) throws IOException
{
BufferedReader buf;
String str;
int n, m;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input your number:");
str=buf.readLine();
n=Integer.parseInt(str);
m=fac(n);
System.out.println("1+2+3+...+n="+m);
}
public static int fac(int n)
{
if(n==1)
return 1;
else
return (fac(n-1)+1);
}
}我的结果
E:\java>java digui1
Input your number:
10
1+2+3+...+n=10
(怎么上一行的结果会等于10呢?)谢谢各位好心的大哥哥帮我改改!
解决方案 »
- 100分求poi、pdfbox,commons包 读(pdf,xls,xlsx,doc,docx,ppt,pptx)的demo
- w3c element getLocalName为null?
- 关于Java调用类里面方法问题
- 关于线程的问题,为何输出如下结果,请高手解释下!
- 在CSDN收索了很久,Tomcat的连接池,如何让它在tomcat启动的时候就全部连接到数据库。
- 跪求:农历转换程式 - 寻求java的代码
- console如何清屏???
- 請問哪里有"JBuilder 3.0/4.0 标准教程"的電子版
- 51digi.com聘请暑期兼职程序员
- Java Map排序
- java socket的半关闭
- SWT tableEditor的问题
{
if(n==1)
return 1;
else
return (fac(n-1)+1);//这一句错了, return (fac(n-1) + n)
}
}
return (fac(n-1)+n);
正解
我想要美女的相片 不想要分~
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
同感
import javax.swing.JOptionPane;int n;
String str=JOptionPane.showInputDialog("Pls enter your number:");
n=Integer.parseInt(str);就OK了!