我想用c语言编写一个程序来交换两个数字。我只是谷歌了c程序中的编码,然后我写的代码是不同的。有某种误解我无法弄清楚。请有人强调我的问题,谢谢。
在这里,我将 num1、num2、temp 作为变量。然后我将 temp 值分配给 num1,因为我知道稍后该 temp 会被分配给 num2 的值(我认为第 4 行和第 5 行将给出第 7 行)由于交换,printf 作为 num1 值作为 num2。然后第 6 行将第 8 行 printf 作为 num2 的值提供给 num1 的值。 不幸的是结果不同
int num1,num2,temp;
printf("give no 1 and no 2 ");
scanf("%d %d",&num1, &num2);
num1=temp;
temp=num2;
num2=num1;
printf("\n After swapping,num1=%d" ,num1);
printf("\n afterswapping, num2=%d",num2);
预计两个数字会被交换,无论我给变量赋予什么值,我收到的输出 num1 为 34,num2 也是 34
最佳答案
你应该这样做:
int num1,num2,temp;
printf("give no 1 and no 2 ");
scanf("%d %d",&num1, &num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("\n After swapping,num1=%d" ,num1);
printf("\n afterswapping, num2=%d",num2);
画一个跟踪表,看看你写的并没有进行交换。 FOA,在 temp 变量中保存一个数字,然后您可以运行用第二个 num 保存的值的变量,紧接着,将您在 temp 中保存的内容放入 num1 中。
请注意,您可以在没有 Temp 变量的情况下以更优雅的方式完成此操作:
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
试试吧!
关于c - 在ci中交换两个数字只需谷歌c程序中的编码然后我写的代码是不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675410/