TEST6
1.实现一个函数,打印乘法口诀表,输入9,输出9x9口诀表,输入12,输出12x12口诀表.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void MultiFor(int n) {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= i; j++) {
printf("%d*%d=%d ", j, i, i*j);
if (i == j) {
printf("\n");
}
}
}
}
int main() {
int n;
printf("please enter n: ");
scanf("%d", &n);
MultiFor(n);
system("pause");
return 0;
}
2.使用函数实现两个数的交换.
#include <stdio.h>
#include <stdlib.h>
void Swap(int* x, int* y) {
int tmp = 0;
tmp = *x;
*x = *y;
*y = tmp;
}
int main() {
int a = 10;
int b = 20;
Swap(&a, &b);
printf("%d %d\n", a, b);
system("pause");
return 0;
}
3.实现一个函数判断闰年
闰年能被400整除,能被4整除并且不能被100整除.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void LeapYear(int year) {
if (year % 400 == 0) {
printf("是闰年\n");
}
else if (year % 4 == 0 && year % 100 != 0) {
printf("是闰年\n");
}
else {
printf("不是闰年\n");
}
}
int main() {
int year;
printf("please enter year: ");
scanf("%d", &year);
LeapYear(year);
system("pause");
return 0;
}
4.创建数组实现初始化数组函数,清空数组函数,逆置数组函数.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void init(int arr[], int len) {
for (int i = 0; i < len; i++) {
arr[i] = i;
}
}
void empty(int arr[], int len) {
int i = 0;
for (i = 0; i < len; i++) {
arr[i] = 0;
printf("%d ", arr[i]);
}
}
void reverse(int arr[], int len) {
int i = 0;
int left = 0;
int right = len - 1;
while (left < right) {
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
}
int menu() {
printf("**********************\n");
printf("*****1.初始化数组*****\n");
printf("*****2. 清空数组 *****\n");
printf("*****3. 逆置数组 *****\n");
printf("**********************\n");
int a = 0;
printf("your choice: \n");
scanf("%d", &a);
return a;
}
int main() {
int a= menu();
int arr[] = { 2,7,9,6,8 };
int len = sizeof(arr) / sizeof(int);
switch (a) {
case 1:
printf("初始化数组: \n");
init(arr, len);
for (int i = 0; i < len; i++) {
printf("%d ",arr[i]);
}
break;
case 2:
printf("清空数组: \n");
empty(arr, len);
break;
case 3:
printf("逆置数组: \n");
reverse(arr, len);
break;
default:
break;
}
system("pause");
return 0;
}
5.实现一个函数判断素数.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int Prime(int n) {
int i = 0;
int j = 0;
j = sqrt(n);
for (i = 2; i <= j; i++) {
if (n%i == 0) {
return 0;
}
}
return 1;
}
int main() {
int n;
int ret;
printf("please enter n(n>1): ");
scanf("%d", &n);
ret = Prime(n);
if (ret == 1) {
printf("%d is a prime number.\n", n);
}
else {
printf("%d is not a prime number.\n", n);
}
system("pause");
return 0;
}