c - 在ci中交换两个数字只需谷歌c程序中的编码然后我写的代码是不同的

标签 c

我想用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/

相关文章:

c++ - 将 vector<string> 转换为 char** C++

c - 如何在C程序和shell脚本之间使用flock

c - 为什么 strtol 返回错误值?

C 显示两者(简单的 if-then)

c - C 程序设计语言 K&R 练习 1- 9

c - Ruby C API `defined? SomeConstant` 等效?

c++ - Bison 解析器计算器

c - pelles c 的奇怪输出

c - 在C中,是否保证数组起始地址小于其他元素的地址?

c - 出于清晰或优化的原因编写冗余程序流程语句?