使用 C++ 指针交换数字

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习如何在 C++ 中使用指针交换两个数字。该程序通过将两个数字的地址传递给函数,并使用指针指向它们在内存中的位置来实现交换。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp(("`C++`")) -.-> cpp/AdvancedConceptsGroup(["`Advanced Concepts`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") cpp/AdvancedConceptsGroup -.-> cpp/pointers("`Pointers`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/variables -.-> lab-96166{{"`使用 C++ 指针交换数字`"}} cpp/function_parameters -.-> lab-96166{{"`使用 C++ 指针交换数字`"}} cpp/pointers -.-> lab-96166{{"`使用 C++ 指针交换数字`"}} cpp/output -.-> lab-96166{{"`使用 C++ 指针交换数字`"}} cpp/user_input -.-> lab-96166{{"`使用 C++ 指针交换数字`"}} cpp/code_formatting -.-> lab-96166{{"`使用 C++ 指针交换数字`"}} end

包含头文件并声明函数

首先,我们包含必要的头文件,并声明一个接受两个整数指针作为参数的 swap 函数。

#include <iostream>
using namespace std;

//Swap function to swap 2 numbers
void swap(int *num1, int *num2);

定义 swap 函数

在这里,我们按如下方式实现 swap 函数:

void swap(int *num1, int *num2) {
       int temp;
       //Copy the value of num1 to some temp variable
       temp = *num1;

       //Copy the value of num2 to num1
       *num1 = *num2;

       //Copy the value of num1 stored in temp to num2
       *num2 = temp;
}

该函数接受两个整数指针作为参数,并使用一个临时变量交换它们所指向的值。

输入两个数字并调用 swap 函数

声明 num1num2 变量,并使用 cin 输入它们的值。调用 swap 函数并传入它们的地址作为参数。

int main() {
       int num1, num2;

       //Inputting 2 numbers from user
       cout<<"Enter the first number : ";
       cin>>num1;
       cout<<"Enter the Second number : ";
       cin>>num2;

       //Passing the addresses of num1 and num2
       swap(&num1, &num2);

输出交换后的数字

使用 cout 输出交换后的数字。

//Printing the swapped values of num1 and num2
cout<<"First number : "<< num1 << endl;
cout<<"Second number: "<<num2 << endl;

编译并运行程序

将程序保存到 ~/project 目录下,文件名为 main.cpp。使用以下命令编译代码:

g++ main.cpp -o main && ./main

总结

在本实验中,我们学习了如何在 C++ 中使用指针交换两个数字。我们声明并定义了一个 swap 函数,用于交换两个整数指针所指向的值,并使用 cincout 分别获取用户输入和显示输出。

您可能感兴趣的其他 C++ 教程