“换汽水”问题(用C++)

来源:互联网 发布:apache服务器安装 编辑:程序博客网 时间:2024/05/21 11:24

算法描述:三个空汽水瓶可以换一瓶汽水。小董有10个空汽水瓶,他最多可以换多少瓶汽水喝?答案:5瓶。

方法如下:先用9个空瓶子换3瓶汽水,然后把这3瓶喝掉以后就有4个空瓶子。然后再用3个换一瓶满的,这时手上有2个空瓶子。然后他再向老板借了一瓶汽水,喝掉这瓶满的,用3个空瓶子换了一瓶满的换个老板。如果小董手上有n个空汽水瓶,最多可以换多少汽水喝?(该代码只测试单个输入,不测试数组)

#include<stdio.h>
#include"iostream"
using namespace std;

int Change(int x) {
    int count=0;
    int a;   //整数
    int b;    //余数
    int c;
    if (x <= 1) {
    
        return 0;

    } if(x==2) {
        count++;
        return count;
    }else if(x >= 3) {
        
        a = x / 3;
        b = x % 3;
        count =a + Change((x / 3)+(x%3));
        
    }
    return count;
}

int main() {
    int buy;
    int total;
    cin >> buy;
    total = Change(buy);
    cout << "cant change " << total << endl;
    system("pause");
    return 0;
}

原创粉丝点击