Exercise in C, change printing

-1

Consider four coins, 25 cents, 10, 5, and 1. Construct a C program that asks the user how much he wants to get back, and then prints out the amount of coins needed to pay the change, number of coins. The program should have a loop that forces the user to enter a positive value.

source:

#include <cc50.h>
#include <stdio.h>

int main (void)
{

int a = 25;
int b = 10;
int c = 5;
int d = 1;
float f = 0;

do
 printf("Quanto de troco deseja receber? ");
 f = GetFloat();
while ( f < 0 );

if ( f == 0 )
 printf("Obrigado volte sempre!\n");

if ( f > 0 )
 printf("Este troco exige %.2f moedas.\n", f);
}
    
asked by anonymous 14.08.2017 / 20:03

2 answers

1

This is a classic college problem.

Basically what you have to do is get the value of the change, and go decreasing by the value of the available currencies, from the highest value coin to the lowest value coin while counting the coins.

follows a possible resolution for the problem

#include <stdio.h>

int main (void)
{

    float a = 0.25;
    float b = 0.10;
    float c = 0.05;
    float d = 0.01;
    float f = 0;

    int moedas;
    do{
        printf("Quanto de troco deseja receber? ");
        scanf("%f",&f);
    }while(f < 0);

    while(f >= a) {
        f -= a;
        moedas++;
    }

    while(f >= b) {
        f -= b;
        moedas++;
    }

    while(f >= c) {
        f -= c;
        moedas++;
    }

    while(f >= d) {
        f -= d;
        moedas++;
    }

    printf("Este troco exige %d moedas.\nObrigado volte sempre!\n", moedas);

}
  

Another question, in C can not change the value of a variable? I tried to use the while loop but did not compile, accused an error saying that I could not change the value of the variable f,

In the case of syntax, you are declaring the same variable f again, so the error is.

float f = GetFloat();

Also, since @Matheus recommends that you use scanf instead of GetFloat() , the code snippet would look like this

scanf("%f",&f);
    
14.08.2017 / 20:31
0

In this part of the code:

do
   printf("Quanto de troco deseja receber? ");
   float f = GetFloat();
while ( f < 0 );

You have forgotten the keys, so you are giving an error. Make:

do{
   printf("Quanto de troco deseja receber? ");
   float f = GetFloat();
}while ( f < 0 );
    
14.08.2017 / 20:15