#include <math.h> #include <stdio.h> int main() { float a, b, c, x1, x2; float delta, real, imag; printf("Enter a, b, c: "); 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); } } printf("Enter a, b, c: "); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 5 int main() { int x, n; srand(time(0)); n = 0; do { n++; x = rand()%10; printf("%3d", x); }while(n<N); printf("\n"); return 0; }
#include<stdio.h> #include<math.h> int main(void){ int n,m,p=0; for(n=101;n<=200;n++){ m=2; while(m<=sqrt(n)){ if(n%m==0) break; m++; } if(m>sqrt(n)){ printf("%d",n); printf(" "); p++;} } printf("\n"); printf("101~200之间共有%d个素数。",p); return 0; }
#include<stdio.h> #include<math.h> int main(void){ long int s; int t=0,i,m; printf("Enter a number:"); scanf("%ld",&s); for(i=0;s!=0;){ m=s%10; if(m%2!=0){ t=m*pow(10,i)+t; i++; } s=s/10; } printf("New number is:%d",t); return 0; }
Key 1:运用与2余数不为零来筛选出奇数,if语句跳过偶数。
Key 2:定义变量i,遇到奇数加一,让取出的奇数乘10^i,循环相加,结果便是自高位到低位(类似于反位数取法)。
#include<stdio.h> #include<math.h> int main(void){ int n,i=1,m=1; double s=0; printf("Enter n(1~10):"); scanf("%d",&n); while(i<=n){ m=m*i; s=s+pow(-1,i-1)/m; i++; } printf("n=%d,s=%lf",n,s); return 0; }
#include<stdio.h> #include <stdlib.h> #include <time.h> int main(){ int day,guess; int chance = 3; srand(time(0)); day = rand() % 31; printf("猜猜2020年12月的哪一天会是你的lucky day"); getchar(); printf("\n开始喽,你有三次机会,猜吧(1~31):"); judge:while(chance--){ scanf("%d",&guess); if(guess==day) return 0; if(guess>day){ printf("\n\n你猜的日期晚了,lucky day悄悄溜到前面啦:(\n"); if(chance==0){ printf("\n\n次数已经用完了,偷偷告诉你,12月,你的lucky day是%d号\n",day); } } if(guess<day){ printf("\n\n你猜的日期早了,lucky day还没到\n"); if(chance==0){ printf("\n\n次数已经用完了,偷偷告诉你,12月.你的lucky day是%d号\n",day); } } } return 0; }