zhuy?
本人化工专业刚学编程20天小白,最近慕课上跟着浙大翁凯学才c语言,多重嵌套有一题有点问题求大佬解答
题目:有1,2,5?角三种硬币,设计程序输入多少元就输出所有硬币组成可能?
?老师给的代码如下
#include <stdio.h>
int main()
{
int x;
int one, two, five;
scanf("%d", &x);
for ( one = 1; one < x*10; one++ ) {
for ( two = 1; two < x*10/2; two++ ) {
for ( five = 1; five < x*10/5; five++ ) {
if ( one + two*2 + five*5 == x*10 ) {
printf("可以用%d个1角加%d个2角加%d个5角得到%d元\n",
one, two, five, x);
break;
}
}
}
}
return 0;
}
比如输入2,就会是以下结果?
?
?然后我想改成两重循环的for语句来满足要求,
#include <stdio.h>
int main()
{
int x;
int one, two, five;
scanf("%d", &x);
for ( one = 1; one < x*10; one++ ) {
for ( two = 1; two < x*10/2; two++ ) {
//for ( five = 1; five < x*10/5; five++ ) {
five=x*10-one-2*two ;
if ( five%5==0) {
printf("可以用%d个1角加%d个2角加%d个5角得到%d元\n",
one, two, five/5, x);
break;
}
}
}
return 0;
}
也输入2?
?
?然后结果就是上面的,一角就只有一个值,5角还用了负值,请问错在哪里?
|