LeetCode 51 N皇后
阿新 • • 發佈:2020-11-12
任務一
#include<stdio.h> #include<math.h> int main(){ float a,b,c,x1,x2; float delta,real,imag; while(scanf("%f%f%f",&a,&b,&c)!=EOF){ if(a==0){ printf("not quadratic equation.\n\n"); }else{ delta=b*b-4*a*c; if(delta>=0){ x1=(-b+sqrt(delta))/(2*a); x2=(-b-sqrt(delta))/(2*a); printf("x1=%.2f,x2=%.2f\n\n",x1,x2); }else{ real=-b/(2*a); imag=sqrt(-delta)/(2*a); printf("x1=%.2f+%.2fi,x2=%.2f-%.2fi\n\n",real,imag,real,imag); } } } return 0; }
任務二
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 #define N 5 5 int main(){ 6 int x,n; 7 srand(time(0)); //缺失此行每次執行數字不在改變 8 n=0; 9 do{ 10 n++; 11 x=rand()%10; 12 printf("%3d",x); 13 }while(n<N); 14 printf("\n"); 15 return 0; 16 }
任務三
#include<stdio.h> int main(){ int sum=0; int count=0; for(int i=101;i<=200;i++){ int mark=0; for(int j=2;j<100;j++){ if(i%j==0){ mark=1; } } if(mark==0){ printf("%d ",i); count++; if(count%5==0){ printf("\n"); } } } printf("%d",count); return 0; }
任務四
#include<stdio.h> #include<string.h> int main(){ char number[50]={0}; while(scanf("%s",number)!=EOF){ int len=strlen(number); for(int i=0;i<len;i++){ if((number[i]-'0')%2!=0){ printf("%c",number[i]); } } getchar(); memset(number,0,50); printf("\n"); } return 0; }
利用字元陣列相當直觀,簡易且不容易出錯。(但注意初始化陣列,getchar()讀取換行符)
任務五
#include<stdio.h> #include<math.h> int main(){ int n; while(scanf("%d",&n)!=EOF){ double temp=1.0; double s=0.0; for(int i=1;i<=n;i++){ if(i%2!=0){ temp=abs(temp*i); }else{ temp=-(temp*i); } s+=1.0/temp; } printf("%lf\n",s); } return 0; }
任務六
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int x=0,n=0; srand(time(0)); while(x==0){ x=rand()%31; } for(int i=0;i<3;i++){ scanf("%d",&n); if(n==x){ printf("lucky day!"); break; } if(n<x){ printf("too early"); } if(n>x){ printf("too late"); } printf("\n"); if(i==2){ printf("luckday is %d!",x); } } return 0; }
11.28生日,surprise!