Like Tree3Likes
  • 2 Post By MK27
  • 1 Post By anduril462

Need a few hints.

This is a discussion on Need a few hints. within the C Programming forums, part of the General Programming Boards category; Hello everyone, ive been a lurker for a few months, signed up recently and now I have some questions. I ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    4

    Need a few hints.

    Hello everyone, ive been a lurker for a few months, signed up recently and now I have some questions.

    I am taking an into to c programming class, its going good so far and I am enjoying it. I was recently given a two part assignment. The first part involved writing a program to convert temperatures from C to F. It was initially challanging for me but after trying multiple items and reading books other than my assigned text, I was able to figure it out.

    The second part of the assignement has taken considerably longer time to plan and understand the logic. I have written and re-written the program so many times that it is to the point now that my previous drafts may have been closer to a solution than the current version. I am working with a peer in my class to solve this problem but we are only able to communicate at night, I was hoping someone might be able to give me a "nudge" so I can make a little progress before this evening.

    The problem is extremly basic but advanced for "week 2" me. The problem asks for a program that mimicks a cash register. The problem asks the user to input how many hamburgers and french fries the user would like. The program should then display the cost of the food, the cost of taxes and the total cost of food plus taxes. The program should continue to loop until the "sentinal value" of a negative number is placed for a "hamburger". Once the loop is exited the total number of orders/customers processed and the total number of sales+tax should be displayed.

    I understand there are way more advanced and streamlined ways to solve the following code, I have only been exposed to the "basics" and that is how the program will need to be written. I have a feeling that the error is in my math, using too many parenthesis or something like that or maybe my coding format. The professor admitted this problem may require us to "reach out" to peers in order to solve.

    I am using ideone online compiler, the code will compile, accept input but I get unexpected results and a handfull of scanf/format warnings. I am seeking hints like "way off", "pay more attention to line ", "your math is wrong", "this part is wrong" etc. If my issue is my understanding of float, double and int please just let me know because I'm obviously not getting it.

    I am not frustrated at all, just realized my time going forward would be better used with a hint or 2.

    Thanks.
    Code:
    #include<stdio.h>
    int main(void)
    {
            double ham=0;     //This is what I came up with for variables. Using double because it was compiling better for me.
     double fri=0;
     double tax=0;
            int cust =0;
     int total=0;
            
    while(ham>=0)                          //Used a while because it made sense and he hinted to wanting that on the assignment sheet, if ham is a negative number it should exit the loop
    {
    ham = 0, fri = 0, tax = 0;             //Initially Fries, Hamburger and Tax will be set to zero, as it loops it will zero out again only recording number of customers and toal sale amount each time.        
     
            printf("How many hamburgers would you like?:\n");  
            scanf("%d",&ham);
            
            printf("How many french fries would you like?:\n");
            scanf("%d",&fri);
                                                      //The printf below is where I think my problem is. It makes sense to me, its basic math but I think it is programmed wrong and screwing up my code.
            printf("Food cost: %d Cost of taxes: %d total cost: %d\n", (ham * 3.5) + (fri * 1.75), ((ham * 3.5) + (fri * 1.75)) * .06, (((ham * 3.5) + (fri * 1.75)) * .06) + ((ham * 3.5) + (fri * 1.75)));
     
    total = total + (((ham * 3.5) + (fri * 1.75)) * .06 + ((ham * 3.5) + (fri * 1.75)); // This should store in "total" the amount plus tax
     
    ++cust; // This should take "cust" which was previously set to zero up top and record each time inputs are entered until a negative number is placed in ham.
     
    }
     
    printf("Total amount of all sales: $%25.2f Total number of customers: %f\n", total, cust); //Once a negative number is placed in ham it should exit the while loop and printf the following, calling from the stored amount in total and cust
     
    return 0;
     
    }
    Last edited by millcityrider; 10-06-2011 at 08:30 AM. Reason: fixed.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    #include<stdio.h>
    int main(void)
    {
            double ham=0;     //This is what I came up with for variables. Using double because it was compiling better for me.
     double fri=0;
     double tax=0;
            int cust =0;
     int total=0;
            
    while(ham>=0)                          //Used a while because it made sense and he hinted to wanting that on the assignment sheet, if ham is a negative number it should exit the loop
    {
    ham = 0, fri = 0, tax = 0;             //Initially Fries, Hamburger and Tax will be set to zero, as it loops it will zero out again only recording number of customers and toal sale amount each time.        
     
            printf("How many hamburgers would you like?:\n");  
            scanf("%d",&ham);
            
            printf("How many french fries would you like?:\n");
            scanf("%d",&fri);
                                                      //The printf below is where I think my problem is. It makes sense to me, its basic math but I think it is programmed wrong and screwing up my code.
            printf("Food cost: %d Cost of taxes: %d total cost: %d\n", (ham * 3.5) + (fri * 1.75), ((ham * 3.5) + (fri * 1.75)) * .06, (((ham * 3.5) + (fri * 1.75)) * .06) + ((ham * 3.5) + (fri * 1.75)));
     
    total = total + (((ham * 3.5) + (fri * 1.75)) * .06 + ((ham * 3.5) + (fri * 1.75)); // This should store in "total" the amount plus tax
     
    ++cust; // This should take "cust" which was previously set to zero up top and record each time inputs are entered until a negative number is placed in ham.
     
    }
     
    printf("Total amount of all sales: $%25.2f Total number of customers: %f\n", total, cust); //Once a negative number is placed in ham it should exit the while loop and printf the following, calling from the stored amount in total and cust
     
    return 0;
     
    }
    You should add some other variables - it's not enough to have "fries", you need a fryNum, and fryCost (if the user inputs their own cost of the food item.

    FryNum, hamNum, etc., would always be an integer - never never deal with floats or doubles, if you don't have to. No one can order half a hamburger, etc.

    When you use scanf(), you need to tell scanf() what data type you want to change. Currently, your format is %d, and the data type you're trying to change is double - change it to the right format.

    Never make a long arithmetic expression. Break it up into smaller expressions, whenever you can. That let's you ensure that it's accurate, before you add the next part and, helps out hugely with any debugging or changes, should it be necessary.

    Work out your math before calling printf(), except for simple/straight forward expressions. That call is a complete *&^%$%$@!

    What are all those parenthesis doing in there? Ye Gods! I've never actually seen a field width for 25 spaces, for a hamburger and fries.
    Last edited by Adak; 10-06-2011 at 09:09 AM.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    4
    Ha! Thanks, I understand what you are saying and this is just the hint I needed. Thanks.

    I'll post what I come up with.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by millcityrider View Post
    I have a feeling that the error is in my math, using too many parenthesis or something like
    As a matter of fact, there is an extra parenthesis on line 22, which should have caused a compiler error. If not, you maybe want a better compiler. Another good thing for this is a syntax highlighting editor -- one that is savvy enough to catch uneven parentheses/braces.

    I am using ideone online compiler,
    What OS are you using? Why don't you just install a compiler? There are good quality free ones available, and it probably won't take you more than half an hour to get it going.

    I get unexpected results and a handfull of scanf/format warnings.
    Yes, your specifiers are backward. %d is for decimal integers (as in base 10 whole numbers, not decimals like 3.2), %lf is for doubles (as in "long" "floating point").

    I am sure you want total to be a double too, not an int. BTW, using floating point for money is error prone because money is not really floating point, it is fixed precision, but for the purpose of your assignment let's put that aside.

    How C treats numbers implicitly is important to understand. By "implicitly", I mean:

    Code:
    4  <-- treated as an int
    4.0 <-- treated as a double
    4.0f <-- treated as a float
    This can affect the outcome of a calculation. For example:
    Code:
    float x = 4/3;
    x is not 1.333333, just because it is a float. 4 and 3 are integers, and dividing one integer by another integer in C yields an integer. So x is actually 1.000. Try it.

    You can get out of that:
    Code:
    float x = (float)4/3;
    or
    float x = 4.0f/3;
    I just mention this in case it turns out to effect some of your calculations. Pay attention to the implicit (and explicit) type of numbers.

    I am seeking hints
    One simple and obvious bad habit I see is repeating the same calculation:

    Code:
    printf("Food cost: %lf Cost of taxes: %lf total cost: %lf\n", 
    	(ham * 3.5) + (fri * 1.75), 
    	((ham * 3.5) + (fri * 1.75)) * .06, 
    	(((ham * 3.5) + (fri * 1.75)) * .06) + ((ham * 3.5) + (fri * 1.75))
    ); 
    total += ((ham * 3.5) + (fri * 1.75)) * .06 + ((ham * 3.5) + (fri * 1.75));
    Some reasons why this is bad:

    1. It's inefficient. That calculation must be done 6 times instead of just once (altho your compiler may be smart enough to spot this and optimize).
    2. It's confusing, because if the calculation is complex, it is not obvious that it is the same each time.
    3. It's error prone and awkward to develop/maintain. If the formula changes, you must change it in 6 different places, and you have 6 opportunities for typos or forgetfulness.


    About point #1: some people may see repeating the calculation as having saved some memory, because you did not have to assign to another variable. That is backward. In general, it is preferable to use memory to save processing power, not use processing power to save memory.

    If my issue is my understanding of float, double and int
    The difference between a float and a double is that a double gets twice as much space in memory. So a double can hold larger/more precise values than a float.

    Finally, I presume some of your formatting problems are due to cut n' paste, but in any case, that is no excuse: you should use proper style and make sure your posts come out that way too. It is not hard. WRT to your code, some of your lines are very long, try to break them, and place long comments on a line by themselves (further broken if required).

    So here it is, the formatting cleaned-up, the repeat calculation removed, the scanfs fixed and total now a double. I'm not saying whether that means everything works correctly, but at least it will be easier for you to debug if you think the output is wrong.

    Code:
    #include<stdio.h>
    
    int main(void) {
    //This is what I came up with for variables. Using double because it was compiling better for me.
    	double ham=0;     
    	double fri=0;
    	double tax=0;
    	int cust =0;
    	double total=0;
    	double base_cost;
    
    //Used a while because it made sense and he hinted to wanting that on the assignment sheet, 
    //if ham is a negative number it should exit the loop
    	while(ham>=0) {
    	//Initially Fries, Hamburger and Tax will be set to zero, 
    	//as it loops it will zero out again only recording number of customers and toal sale amount each time.       
    		ham = 0, fri = 0, tax = 0;             
    		printf("How many hamburgers would you like?:\n"); 
    		scanf("%lf",&ham);
    		printf("How many french fries would you like?:\n");
    		scanf("%lf",&fri);
    		base_cost = ham * 3.5 + fri * 1.75;
    		tax = base_cost * 0.06;
    		//The printf below is where I think my problem is. It makes sense to me, 
    		//its basic math but I think it is programmed wrong and screwing up my code.
    		printf("Food cost: %lf Cost of taxes: %lf total cost: %lf\n", 
    			base_cost, tax, base_cost + tax);
    
    		// This should store in "total" the amount plus tax
    		total += base_cost + tax;
    
    		// This should take "cust" which was previously set to zero up top and
    		// record each time inputs are entered until a negative number is placed in ham.
    		++cust; 
    	}
      
    	//Once a negative number is placed in ham it should exit the while loop and printf the following,
    	//calling from the stored amount in total and cust
    	printf("Total amount of all sales: $%25.2lf Total number of customers: %d\n", total, cust); 
      
    	return 0;
      
    }
    There is one repeated calculation in there (base_cost + tax), but I'm making a judgment call and considering it trivial.
    Last edited by MK27; 10-06-2011 at 09:54 AM.
    Salem and rags_to_riches like this.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Quote Originally Posted by MK27 View Post
    Code:
    printf("Food cost: %lf Cost of taxes: %lf total cost: %lf\n", 
    	(ham * 3.5) + (fri * 1.75), 
    	((ham * 3.5) + (fri * 1.75)) * .06, 
    	(((ham * 3.5) + (fri * 1.75)) * .06) + ((ham * 3.5) + (fri * 1.75))
    );
    "%lf" in printf is wrong and UB, only "%f" for float and double is specified.

  6. #6
    Registered User
    Join Date
    Oct 2011
    Posts
    4
    I am using windows 7 at work, vista at home and xp at school. The professor uses ideone in class so I have stuck with that. I do most of my homework at home and work. Does anyone have a suggestion for a compiler I could use that home and work?

    Thanks everyone. I can tell you put real time into the response and I appreciate that.
    With the idea of doing the math BEFORE the printf and requiring more variables I was able to get everything looking better and actually functioning. After I read the post describing float, double and int I realized I did not understand them correctly, so I went back and re-read that chapter.
    I came up with a code that functioned. However when I used a negative number to try to end the loop it would run the code halfway with that negative number and skew the results. At this point I remembered the professor discussing the “if” statement at the end of our last class. Using the if statement I was able to end the program after negative number was inputed.
    The program now seems to work as the assignment required it to with one exception. When computing the total number of sales the program will round up, of course this is not the case with real money. I think this has something to do with what MK27 stated about money being fixed precision. I understand the issue, I just don’t know how to fix it.
    I’m sure the program could be designed better possibly with fewer variables.
    Code:
    #include<stdio.h>
    int main(void)
    {
            int hamnum=0;   
            int frynum=0;
            double frycost=1.75;
            double hamcost=3.5;
            double ham=0;
            double fry=0;
            float tax=.06;
            double taxnum=0;
            int cust =0;
            double total=0;
    
    while(hamnum>=0)                          
    {
    hamnum = 0, frynum = 0, taxnum = 0;                     
    
            printf("How many hamburgers would you like?:\n");  
            scanf("%i",&hamnum);
    
            if(hamnum<0){printf("Total amount of all sales: $%.2f Total number of customers: %d\n", total, cust);
    
            return 0;}
    
    
    
            printf("How many french fries would you like?:\n");
            scanf("%i",&frynum);
    
            ham=hamnum * hamcost;
            fry=frynum * frycost;
            taxnum=(fry+ham)+((fry+ham)*tax);
    
            printf("Food cost: %.2lf Cost of taxes: %.2lf total cost: %.2lf\n", ham+fry, (ham+fry)*tax, taxnum);
    
    total = total + taxnum; 
    
    ++cust; 
    
    }
    
    return 0;
    
    }



  7. #7
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,444
    What's with the poor indentation and wonky font that broke the code highlighter? Just stick with the standard font, then read Indent cpWiki and pick one of the styles listed in Indent style - Wikipedia, the free encyclopedia (the first 3 are the most common).

    As for your money issue, the idea is to convert all values to pennies and do calculations with integers, only "converting" back to decimal notation at the end. And by converting, we really mean printing out hundreds of pennies (i.e. dollars), and the remainder after all the dollars have been accounted for. Use the integer division (/) and modulus (%) operators.

    EDIT: this means your hamburger cost would look like "int hamcost = 350;", if that helps you out at all.
    Last edited by anduril462; 10-06-2011 at 12:50 PM.
    Salem likes this.

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by millcityrider View Post
    [SIZE=3][COLOR=#000000][FONT=Calibri]I am using windows 7 at work, vista at home and xp at school. The professor uses ideone in class so I have stuck with that. I do most of my homework at home and work. Does anyone have a suggestion for a compiler I could use that home and work
    For Vista and 7 your best bet is Pelles C choose either 32 or 64 bit versions according to your OS. As soon as it's installed, open the help file and start looking around... you will find just about everything you need to get started in there.

  9. #9
    Registered User
    Join Date
    Oct 2011
    Posts
    4
    Thanks for the hint anduril, i made indent changes and I am working on the money portion now.

    tater, downloaded pelles c and I am working with it now, thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Helpful hints anyone?
    By PureMotive in forum C Programming
    Replies: 6
    Last Post: 02-23-2011, 01:13 PM
  2. Need some Hints on how to figure this out.
    By zerlok in forum C++ Programming
    Replies: 6
    Last Post: 02-26-2009, 01:46 PM
  3. Can you give me some hints?
    By mag_chan in forum C Programming
    Replies: 6
    Last Post: 12-05-2005, 03:04 PM
  4. Can you give me some hints?
    By mag_chan in forum C++ Programming
    Replies: 1
    Last Post: 12-04-2005, 01:12 AM
  5. :) Help.. Please... I need some hints
    By NANO in forum C++ Programming
    Replies: 7
    Last Post: 04-16-2002, 03:06 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21