大一上期末复习——编程
九九加法表
#include<stdio.h>
int main()
{
int i, j;
for (i = 1; i <= 9; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d+%d=%2d", i, j, i + j);
}
printf("\n");
}
return 0;
}
排序
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void printA1(int a[], int length);
void sortA1(int a[], int length)
{
int i, j, temp;
for (i = 0; i < length; ++i)
{
for (j = i + 1; j < length; ++j)
{
if (a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void printA1(int a[], int length)
{
int i;
for (i = 0; i < length; ++i)
{
printf("%d,", a[i]);
}
printf("\n");
}
void main()
{
int length = 0;
int a[] = { 12,43,8,50,100,52,0 };
length = sizeof(a) / sizeof(a[0]);
printf("排序前\n");
printA1(a, length);
sortA1(a, length);
printf("选择排序后\n");
printA1(a, length);
system("pause");
}
水仙花数
#include<stdio.h>
void main()
{
int n = 100, i, j, k;
do {
i = n / 100;
j = (n / 10) % 10;
k = n % 10;
if (n == i * i * i + j * j * j + k * k * k)
printf("%d是水仙花数\n", n);
n = n + 1;
} while (n <= 999);
}
最大公约数最小公倍数
#include<stdio.h>
int main()
{
int m, n, a, b, t, c;
printf("Input two integer numbers:\n");
scanf_s("%d%d", &a, &b);
m = a; n = b;
while (b != 0)
{
c = a % b; a = b; b = c;
}
printf("The largest common divisor:%d\n", a);
printf("The least common multiple:%d\n", m * n / a);
}
静态局部变量实例
#include<stdio.h>
int fun(int n);
int main()
{
int i;
for (i = 1; i <= 5; i++)
printf("%d!=%d\n", i, fun(i));
return 0;
}
int fun(int n)
{
static int f = 1;
f = f * n;
return f;
}
判断素数
#include<stdio.h>
#include<math.h>
int count;
int judgePrime(int n);
int main()
{
int i;
printf("The primes between 2 to 100:\n");
for(i=2;i<100;i++)
if (judgePrime(i))
{
printf("%d", i);
count++;
}
printf("The total number of primes: %d\n", count);
return 0;
}
int judgePrime(int n)
{
int i;
int judge = 1;
if (n == 1)
judge = 0;
{
int k = (int)sqrt(n);
for (i = 2; judge && i <= k; i++)
if (n % i == 0)
judge = 0;
}
return judge;
}
指针测试
#include<stdio.h>
void s(int* a, int b)
{
int t = *a; *a = b; b = t;
}
int main()
{
int x = 1, y = 8;
s(&x, y);
printf("%d,%d\n", x, y);
return 0;
}
循环测试——输出素数
#include<stdio.h>
void main()
{
int n, i;
for (n = 3; n <= 100; n = n + 1)
{
for (i = 2; i <= n - 1; i = i + 1)
if (n % i == 0)break;
if (i >= n)printf("%d\t", n);
}
}
循环测试——左下角
#include<stdio.h>
void main()
{
int m, n;
for (n = 1; n <= 9; n = n + 1)
{
for (m = 1; m <= n; m = m + 1)
printf("%4d", m);
printf("\n");
}
}
阶乘算和
#include<stdio.h>
void main()
{
int n, s = 0, t = 1;
for (n = 1; n <= 10; n++)
{
t = t * n;
s = s + t;
}
printf("1+2!+3!...+10!=%d\n", s);
}
|