C第10章-----通过引用传递

#include <stdio.h>

#include <math.h>

 

void metersToFeetAndInches(double meters,unsigned int *ftPtr,double *inPtr){

    //这个函数假定meters的值是非负数

    

    //将meters变量的值转化为feet的值,类型为浮点数

    double rawFeet = meters * 3.281;  //e.g. 2.4536

    printf("rawFeet: %lf\n", rawFeet);

    

    //计算类型为无符号的整形的feet变量的值

    unsigned int feet = (unsigned int)floor(rawFeet);

    printf("ftPtr: %p\n", ftPtr);

    printf("*ftPtr: %d\n", *ftPtr);

    

    //将feet变量的值存储在提供的地址里

    //先检查指针是否为NULL

    if(ftPtr){

        printf("------------------------------------------\n");

        printf("Storing %u to the address %p\n",feet ,ftPtr);

        *ftPtr = feet;

        printf("ftPtr: %p\n", ftPtr);

        printf("*ftPtr: %d\n", *ftPtr);

    }

    

    //计算英寸

    double fractionalFoot = rawFeet - feet;

    double inches = fractionalFoot * 12.0;

    printf("fractionalFoot: %lf\n", fractionalFoot);

    printf("inches: %lf\n", inches);

    

    printf("------------------------------------------\n");

    //将inches变量的值保存到传入的地址

    //先检查指针是否为NULL

    if(inPtr){

        printf("Storing %.2f to the address %p\n", inches, inPtr);

        *inPtr = inches;

        printf("inPtr: %p\n", inPtr);

        printf("*inPtr: %lf\n", *inPtr);

    }

    

}

 

int main(int argc, const char * argv[]) {

    

    double meters = 3.0;

    unsigned int feet;

    double inches;

    

    metersToFeetAndInches(meters, &feet, &inches);

    printf("%.1f meters is equal to %d feet and %.1f inches.",meters,feet,inches);

    return 0;

}

 

结果:

rawFeet: 9.843000

ftPtr: 0x7ffeefbff514

*ftPtr: 0

------------------------------------------

Storing 9 to the address 0x7ffeefbff514

ftPtr: 0x7ffeefbff514

*ftPtr: 9

fractionalFoot: 0.843000

inches: 10.116000

------------------------------------------

Storing 10.12 to the address 0x7ffeefbff508

inPtr: 0x7ffeefbff508

*inPtr: 10.116000

3.0 meters is equal to 9 feet and 10.1 inches.Program ended with exit code: 0

 

posted @ 2019-04-12 14:24  图图图图胡图图  阅读(175)  评论(0编辑  收藏  举报