前言
记录一些关于C语言的小题目,练练手感
题目
1.题目一(a, b, c)
代码如下(示例):
#include <stdio.h>
int func(int a, int b, int c) {
if(b > a && c > b) {
return 1;
} else if(b > c && a > b) {
return 1;
}
return 0;
}
int main(void) {
int a = 13, b = 11, c = 11;
printf("%d\n", func(a, b, c));
return 0;
}
结果如图所示:
2.题目二(1-1/2+1/3-1/4+…+1/99-1/100)
代码如下(示例):
#include <stdio.h>
int main(void) {
int num = 1, i = 0;
double sum = 1;
while(num < 100) {
++num;
if( 0 == (num % 2)) {
sum = sum - 1 / double(num);
} else {
sum = sum + 1 / double(num);
}
printf("%d\t sum = %lf\n", ++i, sum);
}
printf("sum = %f\n", sum);
return 0;
}
结果如图所示:
3.题目三(求整数位数)
代码如下(示例):
#include <stdio.h>
int GetCount(int nValue) {
int i = 0, n = 1;
while(1) {
if( (nValue / n) > 0) {
i++;
n *= 10;
} else {
break;
}
}
return i;
}
int main(void) {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
printf("\n");
printf("这个整数的位数是:%d\n", GetCount(num));
return 0;
}
结果如图所示:
4.题目4(纠错+编写strcpy函数)
代码如下(示例):
#include <stdio.h>
#include <malloc.h>
void GetMemory(char **p, unsigned int size) {
*p = (char*)malloc(size);
return ;
}
char* strcpy(char* dest, char* src) {
if(NULL == dest && NULL == src) {
return NULL;
}
int i = 0;
while( *(src + i) != '\0') {
*(dest + i) = *(src + i);
i++;
}
*(dest + i) = '\0';
return dest;
}
int main(void) {
char* str = NULL, *p = NULL;
GetMemory(&str, 20);
p = strcpy(str, "hello c company\n");
printf(str);
free(str);
return 0;
}
结果如图所示:
5.题目5(余数)
代码如下(示例):
#include <stdio.h>
int GetPhaseNum(void) {
int n = 2, i = 0;
while(n++) {
i = 0;
if(n%2 == 1) {
i++;
}
if(n%3 == 2) {
i++;
}
if(n%5 == 4) {
i++;
}
if(n%6 == 5) {
i++;
}
if(n%7 == 0) {
i++;
}
if(5 == i) {
return n;
}
}
return 0;
}
int main(void) {
printf("答案是:%d\n", GetPhaseNum() );
return 0;
}
结果如图所示:
|