编程环境是vs2013
题目:给定两个整型变量的值,将两个值的内容交换。
代码:
#define _CRT_SECURE_NO_WARNINGS //vs2013中编程时用scanf输入函数时会不安全,所以要加宏定义
#include<stdio.h>
#include<windows.h>
int main()
{
int x, y;
int z = 0;
printf(“Enter the two integers:\n”);
scanf("%d%d", &x, &y);
z = x;
x = y;
y = z;
printf(“After change:x = %d y = %d\n”, x, y);
system(“pause”);
return 0;
}
运行结果:
附加:如果不创建临时变量,怎样交换两个数的内容?
思路:利用加减法交换数值,x,y,先求出x,y的和,然后把x,y的和减去y的值赋给y,再用x,y的和减去赋值后的y的值又赋给x,如此,就交换了x,y的值。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<windows.h>
int main()
{
int x, y;
printf(“Enter the two integers:\n”);
scanf("%d%d", &x, &y);
x = x + y;
y = x-y;
x=x-y;
printf(“After change:x = %d y = %d\n”, x, y);
system(“pause”);
return 0;
}
运行结果:
有问题欢迎评论哦?
本文详细介绍了在VS2013环境下,如何通过使用临时变量和加减法技巧来交换两个整型变量的值,并提供了完整的C语言代码示例。

805

被折叠的 条评论
为什么被折叠?



