C语言中要实现交换两个数的值,可以有很多种方法,具体如下所述. 不使用中间变量: // 异或, a^=b^=a^=b; a ^= b; b ^= a; a ^= b; // 加减 a = a + b; b = a - b; a = a - b; // 乘除 a = a * b; b = a / b; b = a/ b; 使用中间变量: // 需临时空间 temp = a; a = b; b = temp; 正如你所想的那样,上面所示代码只是描述了交换两个数的值的思想,在你实际使用时,还有诸多地方
#include<stdio.h> int main() { //交换两个数的值 // 方法一 可读性最好 ; ; int temp ; temp = a; a = b; b = temp; printf("a = %d, b = %d\n",a, b); //方法二 ; ; c = d - c; d = d - c; c = d + c; printf("c = %d, d = %d\n",c, d); // 方法三 ; ; e = e ^ f; f
#include <iostream> using namespace std; /*值传递,局部变量a和b的值确实在调用swap0时变化了,当结束时,他们绳命周期结束*/ void swap0(int a, int b) { int tem = a; a = b; b = a; } /*没有初始化指针就开始用,该函数是有问题的*/ void swap1(int *a, int *b) { int *tem; /*注意tem没有分配内存*/ *tem = *a; *a = *b; *b = *
1.直接使用算术运算法交换 先把两个数的和赋值给其中一个,然后做减法.例如num1=num1+num2; 此时num2(交换之后)就等于num1减去num2:废话不多说,直接上代码 public class Demo{ public static void main(String[] args){ int a = 10; int b = 20; a = a + b;//此时a=30 b = a - b;//此时b=10 a = a - b;//此时a-b为30-10 System.out.pri
#include <iostream> template<typename T> void exchangeTwoNumber(T &t1, T &t2): void test(); int main() { , b = ; double q = 10.1, w = 20.2; char z = 'z', x = 'x'; std::cout << "交换前的 a = " << a << ", b =
#include <iostream> using namespace std; int main () { ; ; cout<<"a="<<a<<",b="<<b<<endl; a = a+b; ///a=7 b = a-b; ///b=3; a = a-b; ///a=5 cout<<"a="<<a<<",b="&l
[抄题]: Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example