使用函数和指针相互更改两个变量

时间:2022-03-07 19:15:56

I have to change the values of two variables with each other using the following function:

我必须使用以下函数相互更改两个变量的值:

I made this code

我做了这个代码

#include <stdio.h>
#include <stdlib.h>

void change_double(double *d1, double *d2);

int main()
{
    double *a, *b;
    printf("Write two variables of the type double.\n");
    scanf("%d", &a);
    scanf("%d", &b);
    printf("Normal variables: %d %d\n", a, b);
    change_double(&a, &b);
    printf("Changed variables: %d %d\n", a, b);
    return 0;
}

void change_double(double *d1, double *d2)
{
    double aux;
    aux=*d1;
    *d1=*d2;
    *d2=aux;
}

When I run this programm, I generally always get this result(example):

当我运行这个程序时,我通常总是得到这个结果(例子):

Normal variables: 321 123 Changed Variables: 82 321

正常变量:321 123更改的变量:82 321

Number 82 appears for some reason I don't know. Thank you

82号出现由于某种原因我不知道。谢谢

1 个解决方案

#1


2  

Changed Code

改变了代码

#include <stdio.h>
#include <stdlib.h>

void swap_double(double *d1, double *d2);

int main()
{
    double a, b;
    printf("Write two variables of the type double.\n");
    scanf("%lf", &a);
    scanf("%lf", &b);
    printf("Normal variables: %lf %lf\n", a, b);
    swap_double(&a, &b);
    printf("Changed variables: %lf %lf\n", a, b);
    return 0;
}

void swap_double(double *d1, double *d2)
{
    double aux;
    aux=*d1;
    *d1=*d2;
    *d2=aux;
}

#1


2  

Changed Code

改变了代码

#include <stdio.h>
#include <stdlib.h>

void swap_double(double *d1, double *d2);

int main()
{
    double a, b;
    printf("Write two variables of the type double.\n");
    scanf("%lf", &a);
    scanf("%lf", &b);
    printf("Normal variables: %lf %lf\n", a, b);
    swap_double(&a, &b);
    printf("Changed variables: %lf %lf\n", a, b);
    return 0;
}

void swap_double(double *d1, double *d2)
{
    double aux;
    aux=*d1;
    *d1=*d2;
    *d2=aux;
}