so C-programming noob here. I'm working on some practice questions, and I can't seem to figure out where I'm making a mistake on this one.
I'm pretty sure there is an error in how the pointers are being grabbed by the main function, but I've tried everything I could think of/read up on and have no idea how to resolve my problem.
Some more information about the question - the change calculation has to be a function, and I made up a program to get input from the user to then go through the function and spit out the smallest number of bills/coins used. No small change (quarters,dimes,nickels, pennies), so only int number are required.
#include <stdio.h>
#include <math.h>
int main(void)
{
/* local variable definition of enter amount*/
int dollars, *twenties, *tens, *fives, *toonies, *loonies;
printf("enter amount: ");
scanf("%d", &dollars);
printf("\nChange for $%d is:\n", dollars);
/* Calling pay_amount function to get smallest bills*/
printf("$20s: %d\n", &twenties);
printf("$10s: %d\n", &tens);
printf("$5s: %d\n", &fives);
printf("$2s: %d\n", &toonies);
printf("$1s: %d\n", &loonies);
return;
}
/*Function pay_amount declaration */
void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *toonies, int *loonies)
{
while (dollars>=0);
*twenties = (dollars/20);
*tens = ((dollars%20)/10);
*fives = (((dollars%20)%10)/5);
*toonies = ((((dollars%20)%10)%5)/2);
*loonies = (((((dollars%20)%10)%5)%2));
}
unwanted result example:
enter amount: 120
Change for $120 is:
$20s: -4196336
$10s: -4196340
$5s: -4196344
$2s: -4196348
$1s: -4196352
There are several issues with your program. Here are a few of them.
First, you don't want your actual variables to be pointers, but simple ints for you to point to:
int dollars, twenties, tens, fives, toonies, loonies;
Second, you need to pass the actual variable values to printf, not their addresses:
printf("$20s: %d\n", twenties);
printf("$10s: %d\n", tens);
printf("$5s: %d\n", fives);
printf("$2s: %d\n", toonies);
printf("$1s: %d\n", loonies);
Third, you don't actually call your pay_amount function.
Fourth, if you were to call it, it would loop indefinitely due to this completely extraneous loop that you should just remove:
while (dollars>=0);
Fifth; while this isn't actually a bug (it won't stop your program from working in any way), the additional reminder operations in pay_amount are redundant:
*twenties = (dollars/20);
*tens = ((dollars%20)/10);
*fives = ((dollars%10)/5);
*toonies = ((dollars%5)/2);
*loonies = ((dollars%2));
Sixth, as a note on terminology, this has nothing to do with "function pointers", which signify pointers that point to functions, rather than pointers that are passed to functions.
you need change:
/* local variable definition of enter amount*/
int dollars, *twenties, *tens, *fives, *toonies, *loonies;
to
/* local variable definition of enter amount*/
int dollars, twenties, tens, fives, toonies, loonies;
function pay_amount() like this:
pay_amount(int *dollars,int *twenties,int *tens,int *fives,int *toonies,int *loonies)
call function like this: pay_amount(&dollars, &twenties, etc);
and inside the pay_amount() like this:
while (*dollars>=0);
*dollars/20;
*tens = ((*dollars%20)/10);
Related
I am in an intro coding class and I cannot figure out why this program isn't giving me the correct answer and is instead giving me a seemingly random number.
I have tried just putting it as a constant instead of a scanf and it still gives me issues
#include <stdio.h>
const int MIN_CONST = 7;
int ComputeMinutesLost(int userCigarettes) {
int minLost;
int MIN_CONST;
minLost = userCigarettes * MIN_CONST;
return minLost;
}
int main(void) {
int userCigarettes;
printf("How many cigarettes have you smoked?\n");
scanf("%d", &userCigarettes);
printf("You have lost %d minutes to cigarettes. ", ComputeMinutesLost);
return 0;
}
It should just say how many minutes are lost (cigarettes times 7) but it gives a seemingly random number.
Note: The code you posted probably should have flagged you with compile errors, or warnings. Do you have them turned on?
Change the following:
printf("You have lost %d minutes to cigarettes. ", ComputeMinutesLost);
To:
printf("You have lost %d minutes to cigarettes. ", ComputeMinutesLost(userCigarettes));
^------------^ // forgot to include argument
By the way, the numeric value you are seeing is an integer representation of the address of the function ComputeMinutesLost.
Also, (thanks to #unimportant's comment)
in the following code section: //read the comments...
const int MIN_CONST = 7; // one of these...
int ComputeMinutesLost(int userCigarettes) {
int minLost;
int MIN_CONST; // is not necessary, and masks the other
// remove one or the other
// (as is, this one invokes undefined behavior.)
I want to be able to take someones amount owed as the price, and then do some math from the amount received and print my result.
Below is the code I came up with. However, my program does not run after showing the amount tendered.
Any thoughts?
Note, it is my first time coding in C, and I'm from Java..
#include <stdio.h>
int main (void) {
double tendered;
double changeDue;
double price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
int toonoe=0;
int loonie=0;
int quarter=0;
int dime=0;
int nickle=0;
int penny=0;
/* Statements to be executed */
printf("Total purchase price and tendered amount");
scanf("%lf%lf", &price, &tendered);
printf("The sum of %lf and %lf is ", tendered,price);
changeDue=tendered-price;
while(changeDue!=0.00){
if(changeDue<=100.00){
changeDue=changeDue-100.00;
hundred=hundred+1;
}
if(changeDue<=20.00){
changeDue=changeDue-20.00;
twenty=twenty+1;
}
if(changeDue<=10){
changeDue=changeDue-10.00;
ten=ten+1;
}
if(changeDue<=5){
changeDue=changeDue-5.00;
five=five+1;
}
if(changeDue<=2){
changeDue=changeDue-2.00;
toonoe=toonoe+1;
}
if(changeDue<=1){
changeDue=changeDue-1.00;
loonie=loonie+1;
}
if(changeDue>1){
for(int i=0;i<changeDue;i++){
if(i==0.25&&changeDue>=0.25){
changeDue=changeDue-0.25;
quarter=quarter+1;
}
if(i==0.10&&changeDue>=0.10){
changeDue=changeDue-0.10;
dime=dime+1;
}
if(i==0.05&&changeDue>=0.05){
changeDue=changeDue-0.05;
nickle=nickle+1;
}
if(i==0.01&&changeDue<0.05){
changeDue=changeDue-0.01;
penny=penny+1;
}
}
}
}
if(hundred!=0){
printf("%d hundred$ bills given as change",hundred);
}
if(twenty!=0){
printf("%d twenty$ bills given as change",twenty);
}
if(ten!=0){
printf("%d ten$ bills given as change",ten);
}
if(five!=0){
printf("%d five$ bills given as change",five);
}
if(toonoe!=0){
printf("%d toonie coins given as change",toonoe);
}
if(loonie!=0){
printf("%d loonie coins given as change",loonie);
}
if(quarter!=0){
printf("%d quarter coins given as change",quarter);
}
if(dime!=0){
printf("%d dime coins given as change",dime);
}
if(nickle!=0){
printf("%d nicke coins given as change",nickle);
}
if(penny!=0){
printf("%d penny coins given as change",penny);
}
return 0;
}
I have an alternative version of that code, which changes the first part of scanning and printing to
/* identical to start of first version ... */
/* Statements to be executed */
printf("Total purchase price");
scanf("%d", &price);
printf("Enter amount recieved by customer ");
scanf("%d", &tendered);
printf("%d", &tendered);
printf("%d",&tendered);
changeDue=tendered-price;
/* identical to end of first version ... */
And I have a third version, where first scanning and printing is like this.
/* identical to start of first version ... */
float tendered;
float changeDue;
float price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
float toonoe=0;
float loonie=0;
float quarter=0;
float dime=0;
float nickle=0;
float penny=0;
/* Statements to be executed */
printf("Total purchase price");
scanf("%f", &price);
printf("Enter amount recieved by customer ");
scanf("%f", &tendered);
printf("%f tendered", tendered);
changeDue=tendered-price;
/* identical to end of first version ... */
You have the problem of comparing a floating point value for identity
(or for not being identical, same problem) here:
while(changeDue!=0.00){
See here for some background:
Is floating point math broken?
It creates an endless loop (at least if you are not "lucky"), which prevents all further printing. (Actually "lucky" is not a good description for hiding a bug...)
In order to verify this diagnose, insert a printf at the start of the loop.
while(changeDue!=0.00){
printf("Making change...\n");
You will see many more of that debug output line than you expect.
In order to solve that endless-loop problem, change to
while(changeDue>=0.01)
and the endless loop is solved, which currently prevents anything visible happen after printing the due amount.
This does not necessarily fix all the problems in your code, but the most prominent one described in your question is solved.
Note that one of the comments recommends to use int for currency.
I normally agree, but I have accepted your statement that you have to use float/double.
By the way, use the first version of the code.
In the second version you are printing the address of something instead of the value. I.e. the & is wrong here:
printf("%d", &tendered);
In the third version your types and the format string in printf do not match.
I am trying to write a simple program. I am a begineer and i am not getting a value to total. When i am trying to print . I am getting a address as output . Can anyone explain me what is the mistake and correct my program .
#include<stdio.h>
void main()
{
int first,second,total;
printf("enter the value for the first");
scanf("%d",&first);
printf("enter the value for the second");
scanf("%d",&second);
total=power(first,second);
printf("The value for power is %d",power);
}
int power(int doom1,int doom2)
{
int temp=doom1;
int i;
for(i=1;i<=doom2;i++)
{
temp=temp*doom1;
}
return temp;
}
You are printing the wrong variable:
total=power(first,second); //here you are getting return value in variable total
printf("The value for power is %d",power); // power is the function name not variable
Replace this line with:
printf("The value for power is %d",total); // you need to print `total`
Also you have to declare your function prototype before main():
int power(int ,int);
and you should use int main():
int main()
{
// your code
return 0;
}
In addition to passing total to printf instead of power, as you are just starting, make a point to always give your variables an initial value (initialize them). This prevents an attempt to read from uninitialized space which is the bane of new C programmers. (it will save you a lot of headaches). Attempting to read from an uninitialized variable is Undefined Behavior. That can result in anything from slipping by unnoticed, to causing your program to crash. It is to be avoided.
Also, as I explained in the comment, in C, the function main() is type int and it returns a value to its caller (usually the shell, or another program). When using main without arguments, the proper form is:
int main (void)
When accepting arguments, the proper form is:
int main (int argc, char **argv)
In either case, it should return a positive value upon completion. A return 0; at the end is all that is required. exit (0); is another function you can use to return a value. You will also see the form of main with arguments written as:
int main (int argc, char *argv[])
The first and second forms are the practical equivalents of each other, the first recognizing that an array passed to a function in C will decay to a pointer. But for now, just understand that they are equivalent.
You also have an error in your my_power calculation. int temp = doom1; should be int temp = 1; Your calculation was returning a value twice the actual product.
Your style of syntax is up to you, but I would suggest that expanding your syntax a little by using discretionary spaces and lines will make your code much more readable and make finding errors a bit easier. Here is an example regarding all of these points:
#include <stdio.h>
int my_power (int doom1, int doom2);
int main (void)
{
int first = 0; /* Always initialize your variable to prevent */
int second = 0; /* an inadvertant read from an unitialized */
int total = 0; /* value which is Undefined Behavior (bad). */
printf ("\n enter the value for the first : ");
scanf ("%d",&first);
printf (" enter the value for the second: ");
scanf ("%d",&second);
total = my_power (first,second);
printf ("\n The value for my_power is: %d\n\n", total);
return 0;
}
int my_power (int doom1, int doom2)
{
int temp = 1;
int i = 0;
for (i = 1; i <= doom2; i++)
temp = doom1 * temp;
return temp;
}
Output
$ ./bin/simple_function
enter the value for the first : 2
enter the value for the second: 7
The value for my_power is: 128
you are trying to print "power" without parameter
printf("The value for power is %d",power);
you should do
printf("The value for power is %d",total);
or
printf("The value for power is %d",power(first,second));
So, I am led to believe by my professor that when declaring the size of an array, it is best to use #define vs. just declaring it as a normal integer. Is this correct?
If so, why?
Also, if this is correct, what am I doing wrong? When I try to do this I get an message:
error: expected ';', ',' or ')' before numeric constant
every time I call the array. The code works if I just initialize it as an integer.
The definition and usage can be seen in the following code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define handsize 5
#define size 52
// Create function prototypes
void create_deck (int deck[]);
void shuffle_deck (int size, int deck[]);
void display_card (int card);
void display_hand (int size, int hand[]);
int popCard (int *size, int deck[]);
int findScore (int size, int hand[]);
int main()
{
// declare/ initialize variables
int c, d, p, win = 0, lose = 0 , tie = 0, /*handsize = 0, size = 52,*/ deck[size], hand[handsize], dealer[handsize];
char play;
srand(time(NULL)); // attach random number generator to time function for truly random variables
// explain program to user and ask if they want to play
printf("This program is a card game that adds the values of all the\n");
printf("cards in the players hand, and the computers hand. The highest hand wins.\n");
printf("Would you like to play? Please press 'y' for yes, any other key for no.\n");
scanf("%c", &play); // if the user wants to play, continue the program
// while loop that continues as long as the user wants to play
while (play == 'y'){
// call functions to create and shuffle the deck
create_deck(deck);
shuffle_deck (size, deck);
// for loop that calls the popCard function to deal the top card in the deck
for (c = 0; c < 5; c++){
hand[c] = popCard (&size, deck); // player gets a card
dealer[c] = popCard (&size, deck); // computer gets a card
handsize++;
// call the display_hand function to display the individual cards in the players hand
printf("\nYour hand consists of:\n");
display_hand (handsize, hand);
// call the display_hand function to display the individual cards in the dealers hand
printf("Dealer hand consists of:\n");
display_hand (handsize, dealer);
}
// call the findScore function for both the user and the computer
p = findScore (handsize, hand);
d = findScore (handsize, dealer);
// show the value of the user and computers hands
printf("\nThe value of your hand is %i\n", p);
printf("\nThe value of the dealers hand is %i\n", d);
// if statements that keep track of wins, losses and ties
if (p > d)
win++;
if (p == d)
tie++;
if (p < d)
lose++;
// show number of times player has won, lost, tied. Then ask to play again
printf("You have won %i times, tied %i times, and lost %i times\n", win, tie, lose);
printf("\nWould you like to play again?\n");
fflush(stdin); // flush the input buffer to stop false readings
scanf("%c", &play); // read the user input to determine if they want to play again
}
printf("Goodbye");
return 0;
**I hope this is what you wanted
Symbolic constants (either #define or actual constants) are generally preferred.
What happens, for example, when your code is peppered with the value 1440 but you use that number for both twips per inch and kilobytes per floppy (very much showing my age here)?
Then all of a sudden your floppies become 2.88M. You then have to go through all your code looking for 1440 and figuring out if it meant the twips or kilobytes version, and changing the relevant ones. So not only do you have to make the change in multiple places (bad enough), you may also have to figure out whether the change you be made at each place.
Had you instead done:
#define TWIPS_PER_INCH 1440
#define KB_PER_FLOPPY 1440
and then peppered your code with the symbolic names, you could have then just changed one line, without too much thinking or analysis required.
There's a school of thought that any number other than zero or one (and possibly negative one) should have a symbolic constant of some sort. Just make sure you don't make the mistake of doing:
#define FOURTEEN_HUNDRED_AND_FORTY 1440
like one of my minions once tried. I had endless fun trying to explain why that was a bad idea :-)
As to your error, it's certainly possible to declare an array with a preprocessor constant as shown below:
#include <stdio.h>
#include <string.h>
#define VAR 42
int main (void) {
char xyzzy[VAR];
strcpy (xyzzy, "pax is awesome");
puts (xyzzy);
return 0;
}
However, consider the following lines in your code:
#define size 52
void shuffle_deck (int size, int deck[]);
void display_hand (int size, int hand[]);
int popCard (int *size, int deck[]);
int findScore (int size, int hand[]);
hand[c] = popCard (&size, deck);
// and possibly many others.
Because preprocessing is a textual substitution done early in the compilation process, those lines following the first are going to become:
void shuffle_deck (int 52, int deck[]);
void display_hand (int 52, int hand[]);
int popCard (int *52, int deck[]);
int findScore (int 52, int hand[]);
hand[c] = popCard (&52, deck);
and they will cause all sorts of problems, among them that 52 is not a valid variable name in a function prototype, and that you cannot take the address of an integer literal in C because it has no address.
In order to fix this, you define the initial size as a constant:
#define INIT_SZ 52
and use that to set the initial value of a variable size which you can later change, something like:
void doSomethingThatChangesSize (int *pSize) {
(*pSize) += 42;
}
int size = INIT_SZ; // this is the only way you use INIT_SZ
:
doSomethingThatChanges (&size);
I am writing a program that calculates the square of two values (I must use a function.) I am sure that there are many mistakes but, I just can't seem to pick them out:
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int integer1, integer2, total = 0;
int squared(int integer1, int integer2);
int main(void)
{
printf("Enter two numbers to be Squared\n");
scanf("%d%d",&integer1,&integer2);
printf("Square of entered numbers = %d\n", squared(integer1,integer2));
return 0;
}
int squared(int integer1, int integer2)
{
int total;
total = integer1 + integer2;
return total *= total;
}
Header file:
#ifndef HEADER_H
#define HEADER_H
#define squared
int squared(int integer1, int integer2);
#endif
While you don't really need to specify the type int for the arguments that the function squared takes, because int is assumed whenever type is not specified, it is never bad to just put them down, as in:
int squared(int integer1, int integer2, int total);
// instead of
// int squared(integer1, integer2, total);
// both at the prototype and the definition of the function
Then again, you may just leave that out.
There are real problems in your function squared's definition. You aren't using semicolons ;, and you have written a return for the first statement, where I think you don't really want to return anything yet. You probably just wanted:
int squared(int integer1, int integer2, int total)
{
total = integer1 + integer2;
return total *= total;
}
One another important thing is, you are giving 2 less arguments to the squared function call from your main function. squared awaits for 3, you give it just 1. You probably wanted to call it as following:
...
printf("Square of entered numbers = %d\n", squared(integer1, integer2, total));
...
Lastly, you shouldn't be using variables that you haven't given a value to. integer1 hopefully will have a value assigned, integer2 also, hopefully. But total won't be assigned a value by the time you call the squared from main. You can just initialize it with a 0 or something, like this:
...
int integer1, integer2, total = 0;
...
Actually, you don't even need to have a total inside main, your squared function doesn't need a 3rd argument that holds total, as soon as you just declare an int total inside squared. But I won't get to that...
The main issue throughout is that you don't specify the type of each function parameter. You need to tell the compiler that integer1 is an int, for example. Also, see haccks' answer.
Two return statements one after the other are useless. The second return statement is unreachable. And you missed semicolons at the end of both the lines. May be this is the function you wanted:
int squared(int integer1,int integer2,int total)
{
total = integer2+integer2;
return total*total;
}
This calculates the sum of the two values and returns the square of the sum.
in addition to the function definition you need to change even the function call,
printf("Square of entered numbers = %d\n",squared(total));
to
printf("Square of entered numbers = %d\n",squared(integer1,integer2,total));
so that function call gets the value to add. read some basic c programs to know the format and syntax.
With all above answers, you seem to have missed ; in the return statement of your function.