I wanted to enter the argument in cents parameter so that if the argument(cents) is greater than 25, it will go inside the for loop and after dividing by 25 give the remainder. Now, this remainder is saved as the cent's new value, and if it is still greater than 25 it will go inside the loop and same process happen untill we get the last value of cents, which is less than 25.
Along this, I run this count identifier so that every time the loop run it adds up and and tell me how many times the loop runned.
int calculate_quarters(int cents)
{
// TODO
for(int count=0; cents>=25; count )
{
cents = cents%;
}
return cents;
return count;
}
I want to get the value of cent in the end , which is less than 25 and count of how many times loop run.But, every time i run it it gave me this error
undeclared use of identifier 'count'
What I wanted to do suppose, I gave the argument 55 to the function calculate_quarters_, so after running inside the loop, it should give me the value of cents 5 and count is 2 in the end.
CodePudding user response:
Here is a working example demonstrating how to return two values via (out) pointers:
#include <stdio.h>
void calculate_quarters(unsigned cents, unsigned *count, unsigned *remainder) {
*count = cents / 25;
*remainder = cents % 25;
}
int main() {
unsigned cents = 54;
unsigned count;
unsigned remainder;
calculate_quarters(cents, &count, &remainder);
printf("%u cents is %u quarters and %u remainding cents\n", cents, count, remainder);
return 0;
}
CodePudding user response:
In C that's not how the return statement works, if you want to return multiple values you must use a struct. Also, you don't need to use a loop to solve this problem.
I would solve it like this:
If you're learning C I recommend http://beej.us/guide/bgc/
#include <stdio.h>
struct quarter {
int remainder;
int count;
};
struct quarter calculate_quarters(int cents) {
int count = cents / 25;
int remainder = cents % 25;
struct quarter q = {.remainder = remainder, .count = count};
return q;
}
int main(void) {
int cents = 55;
struct quarter q = calculate_quarters(cents);
printf("For %d cents, you have %d quarters and %d cents left over\n", cents,
q.count, q.remainder);
return 0;
}
$ gcc quarter.c -Wall -o quarter
$ ./quarter
For 55 cents, you have 2 quarters and 5 cents left over
CodePudding user response:
your solution were wrong structure like (return
cents and count in the next line) and loop not logic yet because count
is init inside for loop and you return it at outside loop ,so count
cannot define.
I think your problem is you want to count number which can divide 25, how many times ? Here is my suggestion.
int calculate_quarters(int cents)
{
int count = 0;
while (cents >= 25)
{
count ;
cents %= 25;
}
return count;
}
if you want to do in for loop:
int calculate_quarters(int cents)
{
int count;
for (count = 0; cents >= 25; count )
{
cents = cents % 25;
}
return count;
}
Note: if you want to return count
you can initialize it in the beginnning.