C Primer Plus 第十六章 编程练习 1-7题

    xiaoxiao2021-03-25  75

    第2题 #include<stdio.h> #define TK(X,Y) 1/((1/X+1/Y)/2) int main(void) { int i = 10; int j = 5; printf("结果为%.2lf.",TK((double)i,(double)j)); return 0; } 第3题 #include<stdio.h> #include<math.h> #define MID 3.1415926/180 //角度转化弧度 struct rectPoint //直角坐标 { double X; double Y; }; struct lenPoint //极坐标 { double angle; double Len; }; struct rectPoint changeCoordinate(const struct lenPoint* LP); int main(void) { struct rectPoint simpleRect; struct lenPoint simpleLen; printf("请输入坐标角度:"); scanf("%lf",&(simpleLen.angle)); printf("请输入坐标向量长度:"); scanf("%lf",&(simpleLen.Len)); simpleRect = changeCoordinate(&simpleLen); printf("该向量直角坐标为X:%.2lf Y:%.2lf\n",simpleRect.X,simpleRect.Y); return 0; } struct rectPoint changeCoordinate(const struct lenPoint* LP) { struct rectPoint RP; RP.X = (LP->Len) * cos(LP->angle*MID); RP.Y = (LP->Len) * sin(LP->angle*MID); return RP; } 第5题 #include<stdio.h> #include<time.h> #include<stdlib.h> #define LEN 100 #define IX 5 void showArray(const int* ar , int nu); void chooseArray(const int* ar , int Len , int nu); int main(void) { srand((unsigned)time(NULL)); int testArray[LEN]; for(int i = 0 ; i < LEN ; ++i) testArray[i] = rand()%(LEN); showArray(testArray,LEN); chooseArray(testArray,LEN,IX); return 0; } void showArray(const int* ar , int nu) { for(int i = 1 ; i <=nu ; ++i) { printf("%-4d",*(ar+(i-1))); if(i == 0) printf("\n"); } } void chooseArray(const int* ar , int Len , int nu) { int index[nu]; for(int i = 0 ; i < nu ; ++i) index[i] = rand()%Len; for(int i = 0 ; i < nu ; ++i) { for(int j = i ; j < nu ; ++j) { int mid; if(index[i] > index[j]) { mid = index[i]; index[i] = index[j]; index[j] = mid; } } } for(int i = 0 ; i < nu ; ++i) printf("第%d个数为%d\n",index[i]+1,*(ar+index[i])); } 第6题 #include<stdio.h> #include<stdlib.h> #include<string.h> #define Len 50 #define nu 5 struct names { char firstName[Len]; char lastName[Len]; }; void showArray(const struct names* NM , int len); int mycomp(const void* pt , const void* pi); int main(void) { struct names classA[nu] = { {"aa","aaa"}, {"bb","bbb"}, {"ff","fff"}, {"dd","ddd"}, {"ee","eee"}, }; showArray(classA,nu); qsort(classA,nu,sizeof(struct names),mycomp); showArray(classA,nu); return 0; } void showArray(const struct names* NM , int len) { for(int i = 0 ; i < len ; ++i) printf("第%d个人名叫%s.%s\n",i+1,(NM+i)->firstName,(NM+i)->lastName); } int mycomp(const void* pt , const void* pi) { const struct names* N1 = (const struct names*)pt; const struct names* N2 = (const struct names*)pi; int res = strcmp(N1->lastName,N2->lastName); if(res != 0) return res; else return strcmp(N1->firstName,N2->firstName); }
    转载请注明原文地址: https://ju.6miu.com/read-15280.html

    最新回复(0)