Change function parameter double array element

Asked 2 years ago, Updated 2 years ago, 55 views

int main(void)
{

    int a[2];
    double b[2];

    printf ("first person's age, height: \n");
    scanf("%d%lf", &a[0], &b[0]);

    printf ("Second person's age, height: \n");
    scanf("%d%lf", &a[1], &b[1]);

    swap("int", &a, &b);
    swap("double", &a, &b);

    printf ("First Person Age, Height: %d%".1lf\n", a[0], b[0]);
    printf("Second person's age, height: %d%".1lf\n", a[1], b[1]);

    return 0;
}

void swap(char *type, int* a[], double* b[])
{

    double *dtmp;
    int* tmp;

    if (strcmp(type, "int") == 0)
    {
        tmp = a[0];
        a[0] = a[1];
        a[1] = tmp;
    }
    else if (strcmp(type, "double") == 0)
    {       
        dtmp = b[0];
        b[0] = b[1];
        b[1] = dtmp;
    }
}

First : 22187.5 Second : 44 165.4 When you initialize it like this, the age value changes after you execute the function, but the key value does not change. I don't know what the problem is.

double array function c

2022-09-21 11:16

1 Answers

#include <stdio.h>
#include <string.h>

void swap(char *type, int* a, double* b) 

/* Because the default char cannot receive the string "int" or "double" as a parameter, the parameter type is changed to char* */

{
double dtmp; 
int tmp;
/* If the tmp variable is designated as a pointer, it points to the same object, so swap cannot be performed. Therefore, set the local variable int, double to temporarily store the value */
if (strcmp(type, "int") == 0)
{
    tmp = *a;
    a[0] = a[1];
    a[1] = tmp;
    // Modify swap syntax by replacing tmp with general variable

}
else if (strcmp(type, "double") == 0)
{       
   dtmp = *b;
   b[0] = b[1];
   b[1] = dtmp;
}


}


int main(void) 
{
int a[2];
double b[2];

printf ("first person's age, height: \n");
scanf("%d%lf", &a[0], &b[0]);

printf ("Second person's age, height: \n");
scanf("%d%lf", &a[1], &b[1]);

swap("int", a, b);
swap("double", a, b);

printf ("First Person Age, Height: %d%".1lf\n", a[0], b[0]);
printf("Second person's age, height: %d%".1lf\n", a[1], b[1]);

return 0;
}

Some modifications have been made to ensure that the code works properly I've attached the correction details as an annotation in the code.


2022-09-21 11:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.