C编程实现变量值交换、求最大值、顺序输出、最大公约数

来源:互联网 发布:金亚洲软件下载 编辑:程序博客网 时间:2024/05/15 23:50
1. 给定两个整形变量的值,将两个值的内容进行交换。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>

void swap(int x, int y)
{
int tmp = 0;
tmp = x;
x = y;
y = tmp;
printf("After swap:a=%d,b=%d.\n", x, y);
}

int main()
{
int a = 2;
int b = 30;
printf("Before swap:a=%d,b=%d.\n", a, b);
swap(a, b);
system("pause");
return 0;
}
2. 不允许创建临时变量,交换两个数的内容(swap1和swap2分别用加减法和异或法进行交换,两种方法均不用创建临时变量)。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>

void swap1(int x, int y)
{
x = x + y;
y = x - y;
x = x - y;
printf("After swap1:a=%d,b=%d.\n", x, y);
}

void swap2(int x, int y)
{
x ^= y;
y ^= x;
x ^= y;
printf("After swap2:a=%d,b=%d.\n", x, y);
}

int main()
{
int a = 2;
int b = 30;
printf("Before swap:a=%d,b=%d.\n", a, b);
swap1(a, b);
swap2(a, b);
system("pause");
return 0;
}
3. 求10 个整数中最大值。(在数组中对十个数进行处理,在第二个for循环中曾因为写错条件发生越界访问,导致栈溢出)。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>

int main()
{
int arr[10] = { 0 };
int i = 0;
printf("Please input 10 numbers;\n");
for (i = 0; i < 10; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < 9; i++)
{
if (arr[i] > arr[i+1])
{
arr[i] ^= arr[i + 1];
arr[i + 1] ^= arr[i];
arr[i] ^= arr[i + 1];
}
}
printf("The biggest number of 10 numbers is:%d\n", arr[9]);
system("pause");
return 0;
}
4. 将三个数按从大到小输出。(错误点在于起初因为循环次数没有外部循环控制比较的遍数,使得输出结果产生未完全排序的现象)。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>

#define COUNT 3

int main()
{
int i = 0;
int j = 0;
int arr[COUNT] = { 0 };
int count = COUNT;
printf("Please input the numbers:\n");
for (i = 0; i < COUNT; i++)
{
scanf("%d", &arr[i]);
}
while (count--)
{
for (i = 0; i < COUNT-1; i++)
{
if (arr[i] < arr[i + 1])
{
arr[i] ^= arr[i + 1];
arr[i + 1] ^= arr[i];
arr[i] ^= arr[i + 1];
}
}
}
printf("The ordered numbers:\n");
for (i = 0; i < COUNT; i++)
{
printf("%d ", arr[i]);
}
system("pause");
return 0;
}
5. 求两个数的最大公约数(辗转相除法:a%b得余数c,若c=0,则b为最大公约数;若c≠0,则用a=b,b=c,重复执行求余步骤直至余数为0,此时的b为最大公约数)。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>

int main()
{
int a = 0;
int b = 0;
int c = 0;
printf("Please input two numbers:\n");
scanf("%d %d", &a, &b);
while (1)
{
c = a%b;
if (c == 0)
{
printf("The greatest common divisor is %d\n", b);
break;
}
else
{
a = b;
b = c;
}
}
system("pause");
return 0;
}
原创粉丝点击