C語言程式設計練習題庫
阿新 • • 發佈:2019-01-30
1. 題目:寫一個程式,判斷兩個浮點數是否足夠精確。
/* File name:ApproximatelyEqual Function: ensure the accurcy of two numbers.|x-y|/min(|x|,|y|)<e Time: 2018.04.07 edited by QJX */ #include <stdio.h> #include <math.h> double Minfabsnum(double x,double y); //Calculate the min of fabs(x),fabs(y) void GiveInstruction(void); //Give instruction and reference to users #define e 0.0001 //The accurcy double main() { double x,y,c; GiveInstruction(); printf("Please input 2 numers:"); scanf("%lf,%lf",&x,&y); c=Minfabsnum(x,y); if(fabs(x-y)/c<e) printf("Two numers satisfy the accurcy!"); else printf("Two numers not satisfy the accurcy!"); } double Minfabsnum(double x,double y) //Calculate the min of fabs(x),fabs(y) { double a,b; a=fabs(x); b=fabs(y); if(a<=b) return a; else return b; } void GiveInstruction(void) //Give instruction and reference to users { printf("This program can ensure the accurcy of two double numbers!\n"); printf("And the accurcy is 0.0001\n\n"); }
2. 題目:列印楊輝三角前八行
當用更大的資料去測試時,發現最多隻能到13,到需要輸出14行楊輝三角時就會出現錯誤。/* File name:Pascal triangle or YangHui triangle Founction: display the 8 raws of YangHui triangle Time:2018.04.07 edited by qjx */ #include <stdio.h> #define N 8 int Factorial(int n); int Combinations(int n,int k); void GiveInstruction(void); main() { int raw,i,j,k; GiveInstruction(); printf("Please input the raws of YangHui triangle:"); scanf("%d",&raw); for(i=1;i<=raw;i++) { for(j=0;j<raw-i;j++) //print the spacebar { printf(" "); } for(k=0;k<=i-1;k++) //print the YangHui triangle { printf("%4d ",Combinations(i-1,k)); // printf(" "); } printf("\n"); } } int Factorial(int n) //calculate n! { int i,product=1; for(i=1;i<=n;i++) { product*=i; } return product; } int Combinations(int n,int k) //calculate C(n,k)=n!/(k!*(n-k)!) { int a,b,c; a=Factorial(n); b=Factorial(k); c=Factorial(n-k); return a/(b*c); } void GiveInstruction(void) { printf("This program can display the YangHui triangle!\n"); printf("For example:\n"); printf(" 1 \n"); printf(" 1 1 \n"); printf("1 2 1\n"); }
本來以為是超出了int型的範圍,但是手動計算之後並沒有超出啊,而且如果超出的話,在計算12!時,就已經超出範圍了。不解!
解決:還是int範圍的問題
#include <stdio.h> #include <limits.h> #define N 13 int Factorial(int n); main() { int a; a=Factorial(N); printf("%d",a); printf("The value of INT_MAX is %i\n", INT_MAX); printf("The value of INT_MIN is %i\n", INT_MIN); printf("An int takes %d bytes\n", sizeof(int)); } int Factorial(int n) //calculate n! { int i,product=1; for(i=1;i<=n;i++) { product*=i; } return product; }
採用如上程式碼,改變N的值,可以清楚地看到溢位的時刻。
N | N! |
10 | 3628800 |
12 | 479001600 |
13 | 1932053504 |
int | -2147483647~2147483647 |