1.交换两个数的值
创建辅助变量。
#include<stdio.h>
#include<windows.h>
int main()
{
int i = 1;
int j = 2;
int temp;
temp = i;
i = j;
j = temp;
printf(“i=%d,j=%d”, i, j);
system(“pause”);
return 0;
}
2.不用辅助变量进行交换
#include<stdio.h>
#include<windows.h>
int main()
{
int i = 1;
int j = 7;
i = j - i;
j = j - i;
i = j + i;
printf(“i=%d,j=%d”, i, j);
system(“pause”);
}
#include<stdio.h>
#include<windows.h>
int main()
{
int i = 1;
int j = 2;
printf(“i=%d,j=%d”, j, i);
system(“pause”);
}
3.求十个数最大值
#include<stdio.h>
#include<windows.h>
int main()
{
int a[10] = { 1, 2, 3, 4, 5, 4, 233, 23, 445 };
int max = 0;
for (int i = 0; i < 10; i++)
{
if (a[i]>max)
max = a[i];
}
printf(“max=%d”, max);
system("pause");
return 0;
}
4.对3个数从小到大排序
#include<stdio.h>
#include<windows.h>
int sort(int a[], int n) //冒泡算法
{
int t;
for (int j = 0; j < n; j++)
{
for (int i = 1; i <n; i++)
{
if (a[i - 1]>a[i])
{
t = a[i - 1];
a[i - 1] = a[i];
a[i] = t;
}
}
}
}
int main()
{
int a[3] = { 23, 2, 45 };
sort(a, 3);
for (int j = 0; j < 3; j++)
{
printf("%d\n", a[j]);
}
system(“pause”);
return 0;
}