初学者做习题
15.设计一个程序,如以百元钞付款,应找回最少的钱币个数50元,10元,5元,1元各为多少?
//设计一个程序,如以百元钞付款,应找回最少的钱币个数50元,10元,5元,1元各位多少?
public class Xiti4q15 {
//方法一:
/*public static void main(String args[]) {
int n = Integer.parseInt(args[0]); // 假设n是买东西所要付的款
int zhao,wushi,shi,wu; //找零
zhao=100-n;
System.out.println("找您人民币共计" +zhao +"元");
if (zhao>=50){
{wushi=1;
System.out.println("需要50元人民币" +wushi +"张");
zhao=zhao-50;}
}
if (zhao>0 &&zhao>=10){
shi=zhao/10;
System.out.println("需要10元人民币" +shi +"张");
zhao=zhao-(10*shi);
}
if (zhao>0 && zhao>=5){
wu=zhao/5;
System.out.println("需要5元人民币" +wu +"张");
zhao=zhao-(wu*5);}
if (zhao>0 && zhao>=1)
System.out.println("需要1元人民币" +zhao +"张");
} */
// 方法二:
public static void main(String args[]) {
int n = Integer.parseInt(args[0]); // 假设n是买东西所要付的款
int zhao,k; //zhao是 找回零钱的总数,k是找回人民币的张数。
int j=0;
int a[]={50,10,5,1};
zhao=100-n;
System.out.println("找您人民币共计" +zhao +"元");
do {
if (a[j]> zhao)
{j=j+1;
// System.out.println(a[j]);
}
else{
k=zhao/a[j];
System.out.println(a[j]+"元人民币需要" +k +"张");
zhao=zhao-(a[j]*k);
}
}while (zhao>0);
}}
-----------------------------------------------------------------
##################################################################
16.由命令行输入一个正整数n,求下列式子的和。
(a)s=1+1/2+1/3+1/4+...+1/n
(b)s=1-1/2+1/3-1/4+...+1/n
(c)s=1+1/(1*2)+1/(2*3)+...+1/(n*(n+1))
(d)s=1/1!+1/2!+1/3!+...1/n!
/*由命令行输入一个正整数n,求下列式子的和。
(a)s=1+1/2+1/3+1/4+...+1/n
(b)s=1-1/2+1/3-1/4+...+1/n
(c)s=1+1/(1*2)+1/(2*3)+...+1/(n*(n+1))
(d)s=1/1!+1/2!+1/3!+...1/n!
*/
public class Xiti4q16 {
public static void main(String args[]) {
// a
int n = Integer.parseInt(args[0]);
double sum_a = 0;
for (double i = 1; i <= n; i++)
sum_a = sum_a + (1 / i);
System.out.println("(a)s=1+1/2+1/3+1/4+...+1/n的值是:" + sum_a);
// b
double sum_b = 0;
int j = 1;
for (double i = 1; i <= n; i++, j = -j) {
sum_b = sum_b + (1 / (i * j));
}
System.out.println("(b)s=1-1/2+1/3-1/4+...+1/n的值是:" + sum_b);
// c
double sum_c = 0;
for (double i = 1; i <= n; i++) {
sum_c = sum_c + (1 / (i * (i + 1)));
}
System.out
.println("(c)s=1+1/(1*2)+1/(2*3)+...+1/(n*(n+1))的值是:" + sum_c);
//d
double sum_d=0;
for (double i=1; i<=n; i++){
double sum_n=1;
for (double k=1;k<=i;k++){
sum_n=sum_n*k;
// System.out.println(k +"的阶乘是:" + sum_n);
}
sum_d=sum_d+(1/sum_n);
}
System.out.println("(d)s=1/1!+1/2!+1/3!+...1/n! 的值是:" + sum_d);
}
}
-----------------------------------------------------------------
###############################################################(未完待续)
阅读(1625) | 评论(0) | 转发(0) |