设计算法,并用c语言实现。

Python044

设计算法,并用c语言实现。,第1张

#include <stdio.h>

 

int change(int amount, int index, int const coins[]) {

    if(amount == 0) return 1

    if(index <= 0) return 0

    for(int i = amount / coins[index - 1] i >= 0 --i) {

        if(change(amount - i * coins[index - 1], index - 1, coins)) {

            if(i)

                printf(" %d*%d", i, coins[index - 1])

            return 1

        }

    }

    return 0

}

 

int main()

{

    int coins[] = { 20, 50}

    int const size = sizeof(coins)/ sizeof(int)

    int amount

    for(int i = 0  i < size ++i) {

        for(int j = i + 1  j < size ++j) {

            if(coins[i] > coins[j]) {

                int temporary = coins[i]

                coins[i] = coins[j]

                coins[j] = temporary

            }

        }

    }

    if(coins[0] <= 0) {

        printf("数据有误,零钱必须大于0\n")

        return -1

    }

    printf("请输入要兑换的货币金额: ")

    scanf("%d", &amount)

    if(change(amount, size, coins)) 

        printf("\n兑换成功\n")

    else printf("\n兑换失败\n")

    return 0

}

#include

int main() {

int i,x,n,*result = NULL

int a[10],low,high,mid

scanf_s("%d",&n)

// 确保输入的数据是非递减的

for(i = 0 i <n &&i <10 i++) {

scanf_s("%d",&a[i])

}

fflush(stdin)// 如果输入的数组元素多于10个,则废弃

scanf_s("%d",&x)

low = 0,high = n - 1

while(low <= high) {

mid = (low + high) / 2

if(x == a[mid]) {

result = &a[mid]// 这里给出的是查找到该元素的指针

break

}

else if(x <a[mid]) {

high = mid - 1

}

else {

low = mid + 1

}

}

if(result != NULL) {

printf("%d\n",*result)

}

else {

printf("no result\n")

}

return 0

}