在不使用第三个变量的情况下交换两个变量的值——数组
Swapping values of two variables without using a third one- Array
我正在编写一个程序,它接受用户输入来确定一对数字,并交换用户输入的所有对的值。
例如:用户想输入3对,那么他将输入3后跟成对:
31 23 45 6
输出:2 14个36 5
我的程序给出了正确的输出,但不是一次取所有对,而是一个接一个地取它们并给出输出。我有一个模糊的想法,这可以通过使用数组来解决,但不确定如何。请帮助。
下面是我的代码:#include <stdio.h>
int main()
{
int x, y, p, i;
//int a [100], b[100];
printf ("How many pairs?n");
scanf ("%d", &p);
for(i=1; i<=p; i++)
{
printf ("Enter two values:n");
scanf("%d %d",&x,&y);
x = x + y;
y = x - y;
x = x - y;
//a[i]=x;
//b[i]=y;
printf("n");
printf("After Swapping: x = %d, y = %dn", x, y);
}
return 0;
}
当前输出如下:
有几对?2
输入两个值:2 3
交换x= 3和y=2后
输入两个值:4 5
交换x= 5和y=4后。我想让它把所有4个值一起显示输出
我想,你正在寻找这样的东西(你只需要一个数组;您可以直接存储交换顺序的值):
for(i=0; i<p; i++) {
scanf("%d %d",&x,&y);
a[2*i+1]=x;
a[2*i]=y;
}
for(i=0; i<2*p; i++) {
printf("%d ", a[i]);
}
printf("n");
您可以将它们存储在数组中(就像您在某些注释代码中尝试的那样),然后逐个交换它们。
#include <stdio.h>
int main()
{
int x, y, p, i;
printf ("How many pairs?n");
scanf ("%d", &p);
int a[p],b[p];
for(i=0; i<p; i++)
{
printf ("Enter values for pair %d:n", i+1);
scanf("%d %d",&a[i],&b[i]);
}
for(i=0; i<p; i++)
{
x = a[i];
y=b[i];
x = x + y;
y = x - y;
x = x - y;
printf("Pair %d After Swapping: x = %d, y = %dn", i+1, x, y);
}
return 0;
}
试试:http://goo.gl/5JJ7i3
我假设你在C上工作,所以我只使用C头。一种方法是首先找出有多少对,动态地分配空间,用输入的整数填充数组,交换它们,然后打印它们。
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Enter numbers: ");
/* Get the number of pairs. */
int prs;
scanf_s("%i",&prs);
/* Create a dynamic array. */
prs*=2;
int *A = (int*) malloc(prs*sizeof(int));
/* Read the integers into the array. */
int i=0;
for(;i!=prs;scanf_s("%i",&A[i++]));
/* Swap. */
int j=0;
for(;j!=prs;j+=2)
{
int tmp = A[j];
A[j] = A[j+1];
A[j+1] = tmp;
}
/* Print. */
for(i=0;i!=j;printf("%i ",A[i++]));
printf("n");
}
干杯!如果你对真正变得优秀感兴趣,试试这本书。
既然您已经添加了一个c++标记,我将建议一个简单的STL解决方案:
#include <iostream>
#include <vector>
int main(){
std::vector<std::pair<int,int>> Vec;
std::pair<int,int> Pr;
int n;
std::cin>>n; //no. of pairs
while(n--){
std::cin>>Pr.second>>Pr.first; //pair of elements stored in swapped locations
Vec.push_back(Pr);
}
for(auto element : Vec){
std::cout<<element.first<<" "<<element.second<<" ";
}
return 0;
}
相关文章:
- 将数组的地址分配给变量并删除
- 试图让变量检查数组中的某些内容
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 在C++中将变量 wstring 分配给 Char 数组
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- c++ 中的别名变量数组
- 使用类的其他成员变量定义类的成员变量数组
- 可视化 如何在C++中使用复杂变量数组
- 如何 for 循环类变量数组
- 按变量数组中的列将一组整数从文本文件读入
- 运行时C++中的变量数组维度
- C++变量数组
- 将变量(数组类型)从函数传递到"main"范围类型:标准::tr1::match_results<标准::字符串::const_iterator>
- 在堆栈上使用大变量/数组的缺点
- 如何在继承类中创建父类变量数组作为私有成员
- 如何创建一个类变量数组
- 需要以编程方式初始化类变量数组,我怎么做最好
- 直接使用变量(数组中的数据返回相同)或与指针一起使用
- 如何用模板类型初始化成员变量数组