自定义函数
程序员文章站
2022-07-11 15:34:05
...
实现一个函数,打印乘法口诀表,口诀表的行数和列数自己指定。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int Mul(int m){
for (int line = 1; line <= m; ++line){
for (int column = 1; column <= line; ++column){
int ret = line * column;
printf("%d*%d=%2d\t", line, column, m);
}
printf("\n");
}
}
int main(){
int num = 0;
printf("input a number:");
scanf("%d",&num);
Mul(num);
system("pause");
return 0;
}
使用函数实现两个数的交换(指针)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
void Swap(int* x, int* y){
int tmp = *x;
*x = *y;
*y = tmp;
}
int main(){
int i = 10;
int j = 20;
Swap(&i, &j);
printf("i=%d\n", i);
printf("j=%d\n", j);
system("pause");
return 0;
}
实现一个函数判断year是不是润年。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int Isleap(int i){
if (i % 100 != 0){
if (i % 4 == 0){
return 1;
}
printf("\n");
return 0;
}
if (i % 400 == 0){
return 1;
}
return 0;
}
int main(){
int ret = 0;
int year = 0;
printf("input a number:");
scanf("%d", &year);
ret = Isleap(year);
if (ret == 1){
printf("it is a leap year");
}
else{
printf("it is not a leap year");
}
system("pause");
return 0;
}
实现一个函数,判断一个数是不是素数。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int Isprime(int i){
if (i == 1){
return 0;
}
for (int j = 2; j <sqrt(i); j++){
if (i%j == 0){
return 0;
}
}
return 1;
}
int main(){
int num = 0;
int ret = 0;
printf("please input a number:\n");
scanf("%d", &num);
ret=Isprime(num);
if (ret == 1){
printf("is a prime number");
}
else{
printf("is not a prime number");
}
system("pause");
return 0;
}