西南石油大学C语言选修课程序1
上课老师:杜凯
1. 输入成绩分数,输出成绩等级。 #include #include int main() { float score; char grade[10]; printf(\"Please input a score:\"); scanf(\"%f\ switch((int)score / 10) { case 10: case 9: strcpy(grade ,\"Excellent\"); break; case 8: strcpy(grade ,\"Good\");break; case 7: strcpy(grade ,\"Average\"); break; case 6: strcpy(grade ,\"Pass\"); break; case 5: case 4: case 3: case 2: case 1: case 0: strcpy(grade ,\"Failure\"); break; default :strcpy(grade ,\"Error\"); } if(score > 100) strcpy(grade ,\"Error\"); /* if (score > 100) strcpy(grade ,\"Error\"); else if(score >= 90 && score <= 100) strcpy(grade ,\"Excellent\"); else if(score >= 80) strcpy(grade ,\"Good\"); else if(score >= 70) strcpy(grade ,\"Average\"); else if(score >= 60) strcpy(grade ,\"Pass\"); else if (score >= 0) strcpy(grade ,\"Failure\"); else strcpy(grade ,\"Error\");}
*/
printf(\"grade:%s\\n\ return 0;
2.求一元二次方程ax2+bx+c=0的根。 #include #include int main() { float a, b, c; float x1, x2, delta; float real, image; printf(\"请输入一元二次方程的三个系数:\"); scanf(\"%f %f %f\ if(a == 0){ if(b == 0){printf(\"不合法的一元二次方程\\n\"); } else{ x1 = x2 = - c / b;
printf(\"方程是一次方程,有两个相同实根x1=x2=%f\\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=%f x2=%f\\n\}else if(delta == 0){ x1 = x2 = -b / (2 * a);
printf(\"方程是一元二次方程,有两个相同实根x1=x2=%f\\n\
}else{ real = -b / (2 * a); image = sqrt(-delta)/ (2 * a); printf(\"方程是一元二次方程,有两个虚根:\\n\"); printf(\"x1=%f+%fi\\n\ printf(\"x2=%f-%fi\\n\ } } return 0; }
3.求水仙花数,例如151=13+53+13。 #include int main(){ int x, bw, sw, gw; for(x = 100; x <= 999; x++){ bw = x / 100; sw = x % 100 / 10; gw = x % 10; if(bw * bw * bw + sw * sw * sw + gw * gw * gw == x) printf(\"x=%d\\n\ } return 0; }
4.百钱百鸡问题。 #include int main() { int x, y, z; for(x = 1; x < 20; x++) for(y = 1; y < 33; y++) { z = 100 - x - y; if(15 * x + 9 * y + z == 300) printf(\"x=%d y=%d z=%d\\n\ } return 0; }5.选择排序。 #include int main() { int a[10] = {45, 36, 89, 91, 27, 13, 71, 52, 62, 18}, i; int d, t, j; for(i = 0; i < 10; i++) printf(\"%d \ printf(\"\\n\"); for( j = 0; j < 9; j++){ d = j; for(i = j + 1; i < 10; i++) if(a[d] > a[i]) d = i; if(j != d){ t = a[d]; a[d] = a[j]; a[j] = t; }}
for(i = 0; i < 10; i++) printf(\"%d \ printf(\"\\n\"); return 0; }
6.斐波那契数列,f1=1, f2=1, fn=fn-1 + fn-2 #include int main() { int fib[40] = {1, 1}; int i; for(i = 2; i < 40; i++) fib[i] = fib[i - 1] + fib[i - 2]; for(i = 0; i < 40; i++){ printf(\"%10d\ if((i + 1) % 6 == 0) printf(\"\\n\"); } return 0; } 7.