Simplezjz
SimpleMLXG
采纳率67.5%
2020-03-07 19:07

c++求钞票数求大佬帮忙

图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • kukeqq qq284663407 1年前
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    #include <string.h>
    
    struct FaceType {
        int amount;
        int faceValue;
    };
    
    struct MoneyType {
        struct FaceType hundred;
        struct FaceType fifty;
        struct FaceType twenty;
        struct FaceType ten;
        struct FaceType five;
        struct FaceType one;
        //...
    };
    
    int Change(struct MoneyType * money, int sum);
    
    struct MoneyType money = {
        /* 初始数量, 面值 */
        { 0, 100 },
        { 0, 50 },
        { 0, 20 },
        { 0, 10 },
        { 0, 5 },
        { 0, 1 },
    };
    int main(void)
    {
        int sum = 0;
        int size = 0;
        int type = sizeof(MoneyType) / sizeof(FaceType);
        FaceType *face = NULL;
    
        while (1) {
            printf("请输入找零金额: ");
            scanf("%d", &sum);
            size = Change(&money, sum);
            if (size == 0) {
                printf("不需要找零\r\n\r\n");
                continue;
            }
            face = (FaceType *)&money;
            for (int i = 0; i < type; i++) {
                if (face->amount) {
                    printf("%3d元 : %d\r\n", face->faceValue, face->amount);
                }
                face++;
            }
            printf("总张数: \r\n");
            printf("%d\r\n\r\n", size);
        }
        return 0;
    }
    
    int Change(MoneyType * money, int sum)
    {
        FaceType *face = NULL;
        int size = 0;
        int type = sizeof(MoneyType) / sizeof(FaceType);
    
        if (sum == 0) {
            memset(money, 0, sizeof(MoneyType));
            return 0;
        }
    
        face = (FaceType *)money;
        for (int i = 0; i < type; i++) {
            if (sum == 0)
                break;
            face->amount = sum / face->faceValue;
            sum -= face->amount * face->faceValue;
            face++;
        }
    
        face = (FaceType *)money;
        for (int i = 0; i < type; i++) {
            size += face->amount;
            face++;
        }
        return size;
    }
    
    

    ///////////////测试结果: /////////////////////////

    请输入找零金额: 6666
    100元 : 66
     50元 : 1
     10元 : 1
      5元 : 1
      1元 : 1
    总张数:
    70
    
    请输入找零金额: 4567
    100元 : 45
     50元 : 1
     10元 : 1
      5元 : 1
      1元 : 2
    总张数:
    50
    
    请输入找零金额:
    
    
    点赞 评论 复制链接分享
  • dashicaineng 蔡能教授,网站特聘专家 1年前
    点赞 评论 复制链接分享