Revise the C Program so that it can store any two singleprec
Revise the C Program so that it can store any two single-precision numbers inputted by function “scanf()” in two single-precision variables, and then swap the values in these two variables.
#include <stdio.h>
void swap(float *, float *); /* function prototype */
int main()
{
float firstnum, secnum;
printf(\"Enter two numbers: \");
scanf(\"%f %f\", &firstnum, &secnum);
printf(\"\ Before the call to swap() :\ \");
printf(\" The value in firstnum is %5.2f\ \", firstnum);
printf(\" The value in secnum is %5.2f\ \", secnum);
return 0;
}
void swap(float *num1Addr, float *num2Addr)
{
float temp;
temp = *num1Addr; /* save firstnum\'s value */
*num1Addr = *num2Addr; /* move secnum\'s value into firstnum */
*num2Addr = temp; /* change secnum\'s value */
}
Solution
#include <stdio.h>
void swap(float *, float *); /* function prototype */
int main()
{
float firstnum, secnum;
printf(\"Enter two numbers: \");
scanf(\"%f %f\", &firstnum, &secnum);
printf(\"\ Before the call to swap() :\ \");
printf(\" The value in firstnum is %5.2f\ \", firstnum);
printf(\" The value in secnum is %5.2f\ \", secnum);
swap(&firstnum,&secnum); //call the swap function
printf(\"\ After the call to swap() :\ \"); //value after calling the swap function
printf(\" The value in firstnum is %5.2f\ \", firstnum); //print value of firstnum,which now contain value of secnum
printf(\" The value in secnum is %5.2f\ \", secnum);//print value of secnum,which now contain value of firstcnum
return 0;
}
void swap(float *num1Addr, float *num2Addr)
{
float temp;
temp = *num1Addr; /* save firstnum\'s value */
*num1Addr = *num2Addr; /* move secnum\'s value into firstnum */
*num2Addr = temp; /* change secnum\'s value */
}
********OUTPUT*****
sh-4.3$ gcc -o main *.c
sh-4.3$ main
Enter two numbers: 12.22 13.33
Before the call to swap() :
The value in firstnum is 12.22
The value in secnum is 13.33
After the call to swap() :
The value in firstnum is 13.33
The value in secnum is 12.22
********OUTPUT*****
Note:Code has been tested on gcc compiler,please ask in case of any doubt,Thanks.
