1、将一个数倒转输出:
(1)限定使用递归,第一反应想到的方法 :
1 #include<stdio.h> 2 int array[10]; 3 int i=0; 4 void convert(int n){ 5 if(n==0) 6 return; 7 else{ 8 array[i++]=n%10; 9 convert(n/10); 10 } 11 } 12 13 int main(){ 14 int number=12345; 15 convert(number); 16 for(int j=0;j<i;j++){ 17 printf("%d",array[j]); 18 } 19 }
(2)使用数组指针:
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 void convert(int * result,int num){ 5 if(num>10) 6 convert(result +1,num/10); 7 *result=num%10; 8 } 9 10 int main(){ 11 int number=12468; 12 int result[10]={-1}; 13 convert(result,number); 14 printf("%d ",number); 15 for(int i=0;i<10;i++) 16 if(result[i]>0) 17 printf("%d",result[i]); 18 }
2、输出学生的成绩大于平均成绩的学生:
(1)C 语言版用递归:
1 /* 2 这里有一个疑问:在加与不加return average, average的值在每次返回的时候是一样的 3 按理说,如果不加return average的值每次average的值应该不一样 ? 除非 average每次递归后保存一次值 4 */ 5 6 #include<stdio.h> 7 double find(int total,int n){ 8 int number,score,average; 9 scanf("%d",&number); 10 if(number!=0){ 11 scanf("%d",&score); 12 average=find(total+score,n+1); 13 if(score>=average){ 14 printf(" number=%d: score=%d ",number,score); 15 } 16 printf(" average=%d ",average); 17 // return average; 18 }else{ 19 printf("Average=%d ",total/n); 20 return total/n; 21 } 22 } 23 24 int main(){ 25 find(0,0); 26 }
(2)Java用的for循环:
1 package employeer_algorithm; 2 3 import java.util.Scanner; 4 5 class Student { 6 private String name=""; 7 private double store=0; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public double getStore() { 15 return store; 16 } 17 public void setStore(double store) { 18 this.store = store; 19 } 20 } 21 public class Test{ 22 public static void main(String args[]){ 23 double sum=0; 24 Student students[]= new Student [5]; 25 System.out.println("Please input informations of students:"); 26 Scanner sc = new Scanner(System.in); 27 for(int i=0;i<students.length;i++){ 28 System.out.println("The informations of"+i+"th student are format as name,store "); 29 students[i]= new Student();//刚开始的时候没有进行new 对象,以为在开辟数组的时候已经new好 30 students[i].setName(sc.next()); 31 students[i].setStore(sc.nextDouble()); 32 sum+=students[i].getStore(); 33 } 34 double average = sum/students.length; 35 for(int i=0;i<students.length;i++){ 36 if(average<students[i].getStore()) 37 System.out.println(students[i].getName()+"'s score above average store"); 38 } 39 40 } 41 }
3、组合问题:从M个不同字符中选择N个字符的不同组合:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<cmath> 4 void find(char *source, char *result, int n){ 5 if(n==1){ 6 while(*source){ 7 printf("%s %c ",result,*source++); 8 } 9 }else{ 10 int i,j; 11 for(i=0;source[i]!=0;i++); 12 for(j=0;result[j]!=0;j++); 13 for(;i>=n;i--){ 14 result[j]=*source++; 15 result[j+1]='