zoukankan      html  css  js  c++  java
  • c语言 10-1

    1、如果小于0,修改为150, 大于100,修改为100

    #include <stdio.h>
    
    void adjust(int *x)
    {
        if(*x < 0)
            *x = 150;  //变量的值作为了下一个判断条件,如何避免?
        if(*x > 100)
            *x = 100;    
    } 
    
    int main(void)
    {
        int a;
        puts("please input an integers.");
        printf("a = "); scanf("%d", &a);
        
        adjust(&a);
        puts("
    =================");
        printf("a  = %d
    ", a);
        
        return 0; 
    }

    改进:

    #include <stdio.h>
    
    void adjust(int *x)
    {
        if(*x < 0)
        {
            *x = 150;
            return;
        }
        if(*x > 100)
        {
            *x = 100;
            return;
        }
    } 
    
    int main(void)
    {
        int a;
        puts("please input an integers.");
        printf("a = "); scanf("%d", &a);
        
        adjust(&a);
        puts("
    =================");
        printf("a  = %d
    ", a);
        
        return 0; 
    }

    言归正传:

    #include <stdio.h>
    
    void adjust(int *x)  // 形参声明为指针  数据类型 + 指针运算符 + 变量名,告诉函数接受的参数为指针 
    {
        if(*x < 0)  //在函数体中使用指针运算符+指针,获取指针所指的对象,相当于对象的别名,对别名进行修改,相当于对原始变量进行修改 
        {
            *x = 0;
            return;
        }
        if(*x > 100)
        {
            *x = 100;
            return;
        }
    }
    
    int main(void)
    {
        int a = -10;
        int b = 10;
        int c = 110;
        
        adjust(&a); // 实参给与指针, 取址运算符 + 对象,获取地址,生成指针。 
        adjust(&b);
        adjust(&c);
        
        puts("
    =============");
        printf("a = %d
    ", a);
        printf("b = %d
    ", b);
        printf("c = %d
    ", c);
        
        return 0; 
    }

    要想在函数中对变量进行修改,需要传入该变量的指针,然后再函数体中使用指针运算符*+指针,获取变量的别名,对别名进行处理,相当于对原始变量进行处理。

  • 相关阅读:
    mysql drop table & myisam
    python 发送 html email
    python mysqldb 查询返回字典结构
    shell 脚本 连接数据库
    python 中使用map 构建sql查询语句
    C#启动一个外部程序(1)WinExec
    知道在那里划这一条线吗[zt]
    C#启动一个外部程序(2)ShellExecute
    把FlashCom 帮助安装到Flash 8 中文版
    C#读写ini文件
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14828169.html
Copyright © 2011-2022 走看看