zoukankan      html  css  js  c++  java
  • c语言中具有结构体成员的结构体

    c语言中具有结构体成员的结构体。

    1、

    #include <stdio.h>
    #include <math.h>
    
    #define sqr(x) ((x) * (x))
    
    typedef struct{
        double x;
        double y;
    } Point;
    
    typedef struct{
        Point pt;
        double fuel;
    } Car;
    
    double dist(Point a, Point b)  // 计算两点之间距离的程序 
    {
        return sqrt(sqr(a.x - b.x) + sqr(a.y - b.y));
    }
    
    void put_info(Car x)  // 显示car型结构体各个构成元素, 当前的坐标, 当前的燃料 
    {
        printf("current position: %.2f  %.2f
    ", x.pt.x, x.pt.y);
        printf("remaining fuel: %.2f
    ", x.fuel);
    }
    
    int move(Car *now, Point des)  // 进行移动的程序,形参为Car型结构体,和Point型结构体 
    {
        double d = dist(now -> pt, des);  // 利用dist函数计算当前坐标到目标的距离 
        if(now -> fuel < d)  // 如果燃油低于距离,返回0,(1个单位燃料,1个单位距离) 
            return 0;
        now -> pt = des;  // 将当前的坐标改为目标地的坐标 
        now -> fuel -= d;  // 当前的燃油减去距离(耗油量) 
        return 1;
    }
    
    int main(void)
    {
        Car begin = {{0.0, 0.0}, 90.0};  // 声明起始位置 
        
        while(1)
        {
            int choose;
            Point dest;  // 声明目的地结构体 
            put_info(begin); // 显示当前的坐标,燃料 
            printf("start -> 1; no star -> 0: ");  // 选择是否启动 
            scanf("%d", &choose);
            if(choose != 1)
                break;
            printf("x-axis dest: "); scanf("%lf", &dest.x);  // 输入目的地坐标 
            printf("y-axis dest: "); scanf("%lf", &dest.y);
            if(!(move(&begin, dest)))    // 如果move的返回值为0, 输出燃料不足提示信息。 
                puts("fuel sortage, unable to drive!!!");    //程序结束的条件时输入非1的数字 
        }
        return 0;
    }

  • 相关阅读:
    Servlet深层知识
    HTTP协议
    Web开发中的主要概念
    Schema约束
    连接池基础
    Mysql基础3
    JDBC常用接口详解
    Mysql基础2
    Mysql基础1
    使用12c的DBCA创建数据库的时候报错TNS-04404
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14850886.html
Copyright © 2011-2022 走看看