View Full Version : C++ Help
sixstorm
Oct 3, 2006, 04:45 PM
Hello all experienced more than me people! :D I have a very urgent favor to ask of you all. I have an intro to C++ class online and I am doing a project, which is very confusing. It is about functions and for some reason, the class program or XCode doesn't want to seem to wanna build some obvious things. For example, here is a very very basic version of my program (without anything related to functions at all, I like to build from the ground up :D):
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double breakfast = 5.50;
double bDiscount = .10;
double quanBreak = 10;
double discountAmt, subTotal, totalOne, breakfastTotal;
int breakfastMeals;
cout << "Enter the number of Breakfast Meals ordered: ";
cin >> breakfastMeals >> endl;
totalOne = breakfastMeals * breakfast;
if (breakfastMeals >= quanBreak);
discountAmt = totalOne / bDiscount;
subTotal = totalOne - discountAmt;
breakfastTotal = subtotal * .10;
else
breakfastTotal = totalOne * .10;
cout << "Your Total Is: " << breakfastTotal << endl;
return 0;
}
I get a build error on the first "cin >>" line!!! WTF? It's never done this before and I have no clue what it is. But like I always say, two sets of eyes are better than one. Obviously, I'm missing something . . . Any suggestions? And please, I deserve to be called a n00b for this one prolly so feel free.
uaaerospace
Oct 3, 2006, 05:16 PM
Try removing the ">> endl" from the cin statement.
Also, keep program scope in mind when writing if statements. The proper structure for an if statement is
if (argument)
{
statement;
statement;
}
You have to use the {}'s unless you just have one statement. In your code, you have 3 statements, so the {}'s are needed.
Also...there is no if-else statement in c++. Use another if statement.
haha...Also. Keep in mind that coding in c++ is usually if not always case sensitive. You may wish to check your use of subtotal vs. subTotal. You are using a good convention (camelCase), just stick with it.
deputy_doofy
Oct 3, 2006, 05:20 PM
Try removing the ">> endl" from the cin statement.
Yes. That's exactly it.
endl means ENDLINE, (which basically puts the next output on the next line) and you would only use that for output.
sixstorm
Oct 3, 2006, 05:29 PM
Try removing the ">> endl" from the cin statement.
Also, keep program scope in mind when writing if statements. The proper structure for an if statement is
if (argument)
{
statement;
statement;
}
You have to use the {}'s unless you just have one statement. In your code, you have 3 statements, so the {}'s are needed.
Also...there is no if-else statement in c++. Use another if statement.
Thanks for the help, I can't believe I didn't see that. What do you mean there is no if-else statement in C++? Don't think I'm calling you a liar, but I've been using If-Else statements for weeks now . . . unless I am reading your statement wrong. Geez, what a day lol.
deputy_doofy
Oct 3, 2006, 05:34 PM
Thanks for the help, I can't believe I didn't see that. What do you mean there is no if-else statement in C++? Don't think I'm calling you a liar, but I've been using If-Else statements for weeks now . . . unless I am reading your statement wrong. Geez, what a day lol.
There IS an if (then) statement. Well, there's no THEN...
if (comparison)
{
// Do stuff and things.
// Do more stuff and things.
}
else
{
// Do completely different stuff and things.
// Do MORE completely different stuff and things.
}
uaaerospace
Oct 3, 2006, 05:36 PM
What do you mean there is no if-else statement in C++? Don't think I'm calling you a liar, but I've been using If-Else statements for weeks now . . . unless I am reading your statement wrong.
hmm, well, it compiles fine with the if/else command in xCode, however the text I have on c++ mentions no such command. Also, when taking c++ classes, we always used if statements. Perhaps it's just personal preference of my professors. Oh well, I learn something new every day....this time from a self proclaimed "noob" :p :D
bousozoku
Oct 3, 2006, 05:37 PM
Thanks for the help, I can't believe I didn't see that. What do you mean there is no if-else statement in C++? Don't think I'm calling you a liar, but I've been using If-Else statements for weeks now . . . unless I am reading your statement wrong. Geez, what a day lol.
The way you have it, the statement discountAmt = totalOne / bDiscount; is executed for the if. The semicolon doesn't belong on the statement with the if.
The other statements, had it compiled, except for the else would be executed without condition.
When confused, use the braces {} to explicitly declare the block.
sixstorm
Oct 3, 2006, 06:03 PM
Thanks a lot for the help. I played and tinkered for a little bit and finally got it to work. I do have to take out a lot of "//" in my program (there's a lot more to the program lol) and add my function. I'm sure I'll be back here soon with more Q's. Thanks again everybody.
Heath
Oct 3, 2006, 06:25 PM
You might want to revisit that if statement again.
You had:
if (breakfastMeals >= quanBreak);
This will not execute any conditional logic because of the semicolon at the end.
It will process the if statement, then merrily execute code that immediately follows, regardless of the outcome of that comparison.
(At least this was the case the last time I touched C++, ymmv).
sixstorm
Oct 3, 2006, 06:25 PM
Here we go again. I'm trying to use a function now . . . here's the full code:
#include <iostream>
#include <iomanip>
using namespace std;
double calcDiscount (int quantity, double costEach, double discountPerCent, int orderMoreThan);
int main()
{
double breakfast = 5.50;
double bDiscount = .10;
double quanBreak = 10;
double breakfastTotal;
int breakfastMeals;
cout << "Enter the number of Breakfast Meals ordered: ";
cin >> breakfastMeals;
breakfastTotal = calcDiscount (breakfastMeals, breakfast, bDiscount, quanBreak);
cout << "Your total is: "<< breakfastTotal << endl;
}
double calcDiscount (int quantity, double eachCost, double discountPerCent, int orderMoreThan);
{
double discountAmt, totalOne, subTotal;
totalOne = quantity * costEach;
if (quantity >= orderMoreThan)
{
discountAmt = totalOne * bDiscount;
subTotal = totalOne - discountAmt;
}
else
{
subTotal = totalOne * .10;
}
return subTotal;
}
It's giving me errors on subTotal and totalOne with "no type" (whatever that means) and a few other things. Any ideas?
bousozoku
Oct 3, 2006, 06:30 PM
Here we go again. I'm trying to use a function now . . . here's the full code:
It's giving me errors on subTotal and totalOne with "no type" (whatever that means) and a few other things. Any ideas?
Watch where you put your semicolons.
Note the difference between your definition of main() and your definition of calcDiscount().
sixstorm
Oct 3, 2006, 06:38 PM
Watch where you put your semicolons.
Note the difference between your definition of main() and your definition of calcDiscount().
I've got both definitions in {}s, so that shouldn't be a problem. BTW, I'm using a remote terminal (via OSX terminal, which is a PITA) and it's giving me different errors than XCode is. XCode is a bit easier to work with.
bousozoku
Oct 3, 2006, 06:42 PM
I've got both definitions in {}s, so that shouldn't be a problem. BTW, I'm using a remote terminal (via OSX terminal, which is a PITA) and it's giving me different errors than XCode is. XCode is a bit easier to work with.
Let me put it plainly: you have a semicolon between the closing parenthesis and the opening brace.
sixstorm
Oct 3, 2006, 06:46 PM
Let me put it plainly: you have a semicolon between the closing parenthesis and the opening brace.
If I'm not being a PITA for ya, could you explain why I wouldn't put it there? Just trying to learn . . .
Heath
Oct 3, 2006, 06:55 PM
Try to explain why you WOULD put it there.
double calcDiscount (int quantity, double eachCost, double discountPerCent, int orderMoreThan);
The semicolon is usually an indication to the compiler that you're done whatever it is you are going to do in that statement.
So you're telling the compiler, 'Hey I'm done defining my function!' and it goes 'alright.. an empty function.. gotcha.. what's the rest of the code for then?' and proceeds to spew errors at you that make no sense :)
sixstorm
Oct 3, 2006, 07:01 PM
Try to explain why you WOULD put it there.
double calcDiscount (int quantity, double eachCost, double discountPerCent, int orderMoreThan);
The semicolon is usually an indication to the compiler that you're done whatever it is you are going to do in that statement.
So you're telling the compiler, 'Hey I'm done defining my function!' and it goes 'alright.. an empty function.. gotcha.. what's the rest of the code for then?' and proceeds to spew errors at you that make no sense :)
Okee dokee, that makes sense. Now tell me this. Take a look at my identifiers, my function call and my function definition header. Why am I still getting an errors about "assignment 'int' to 'double'"? If in a function call, it makes the temp memory cells from left to right, it shouldn't have a problem defining those temp memory cells for this.
EDIT: Guess I should give you some code huh?
int quanBreak = 10;
int breakfastMeals;
double bDiscount = .10;
double breakfast = 5.50;
double calcDiscount (int quantity, double costEach, double discountPerCent, int orderMoreThan)
Heath
Oct 3, 2006, 07:08 PM
It looks like you're trying to stuff a double into an int, not the other way around.
double calcDiscount (int quantity, double costEach, double discountPerCent, int orderMoreThan);
double quanBreak = 10; <-- this won't fit into an int even though it looks like it should.
breakfastTotal = calcDiscount (breakfastMeals, breakfast, bDiscount, quanBreak);
You are correct in that the ints can be implicitly converted to doubles, but the last argument you are passing in a double into an int, and the compiler will complain about that one since it can result in the loss of information.
sixstorm
Oct 3, 2006, 07:14 PM
It looks like you're trying to stuff a double into an int, not the other way around.
double calcDiscount (int quantity, double costEach, double discountPerCent, int orderMoreThan);
double quanBreak = 10; <-- this won't fit into an int even though it looks like it should.
breakfastTotal = calcDiscount (breakfastMeals, breakfast, bDiscount, quanBreak);
You are correct in that the ints can be implicitly converted to doubles, but the last argument you are passing in a double into an int, and the compiler will complain about that one since it can result in the loss of information.
I changed the "double quanBreak" into "int quanBreak" (that's what it's supposed to be, but I'm still getting errors on my function call. Why won't 10 go into an int like that?
ifjake
Oct 3, 2006, 07:41 PM
I'm also in a beginners C++ course and am looking at some of your stuff and comparing it to how I'm being taught.
I'm actually interested in your #include statements and such.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
We use <iostream.h> which means that the std::cout stuff and
using namespace std; aren't needed. But I feel like we're using outdated stuff. If this is all it takes to move to newer stuff I might do that on my own. But is <iomanip> needed to state using namespace std;?
Are there any similar steps that need to be taken when moving from <fstream.h> to <fstream>?
bousozoku
Oct 3, 2006, 07:46 PM
I'm also in a beginners C++ course and am looking at some of your stuff and comparing it to how I'm being taught.
I'm actually interested in your #include statements and such.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
We use <iostream.h> which means that the std::cout stuff and
using namespace std; aren't needed. But I feel like we're using outdated stuff. If this is all it takes to move to newer stuff I might do that on my own. But is <iomanip> needed to state using namespace std;?
You're right. You're using C++ prior to the ISO and ANSI standards.
ifjake
Oct 3, 2006, 07:51 PM
You're right. You're using C++ prior to the ISO and ANSI standards.
What do I need to do to get stuff to work right with these new standards?
YoNeX
Oct 3, 2006, 08:13 PM
Ahh yes memories of the introduction C++ class. My criticism is why do you need the iomanip and the cmath libs? From the code, I don't see any any purpose for these libs from the code given. Another pointer I can give you is try to use abbreviations for your function names. You are prone to make less mistakes if you use abreviations. For example instead of entering in quantity, use qty. Instead of breakfast, you can use bfast. These small little thing will add up, plus you avoid line wrapping (or having long horizontal code). Oh yeah, forgot, don't need to take my advice, many people have different style of coding. Use what you like (or use based on the school's coding style).
sixstorm
Oct 3, 2006, 08:19 PM
Anyone know why I'm getting a "int from double" error, even though my code is going "int to int"?
Heath
Oct 3, 2006, 08:25 PM
Anyone know why I'm getting a "int from double" error, even though my code is going "int to int"?
What line is giving you the issue?
sixstorm
Oct 3, 2006, 08:27 PM
What line is giving you the issue?
My function call.
YoNeX
Oct 3, 2006, 08:35 PM
Remember you will spend around 20% coding, and 80% debugging. So stare at your code for a little bit, and scream out some obscentity, and you will eventually get it. Worked for me. :D
By the way, your function call, its suppose to be (int, double, double, double) or make quanBreak an int instead of a double.
Heath
Oct 3, 2006, 08:41 PM
I'll assume you mean this line:
breakfastTotal = calcDiscount (breakfastMeals, breakfast, bDiscount, quanBreak);
I ran it through a compiler and found a few things.
If you notice, what you're getting is actually a warning, not an error (regarding this line anyway). You should correct this, however it will not stop your compile. However the error that IS stopping it is the case of pesky typos and a scope issue.
In your function, you are using a variable called costEach, but in the header where you define the function you have called it eachCost, the compiler hates that!
Also you are typing to use the variable bDiscount in your function; the way that you currently have it set up you function cannot see this variable to use it since it is not declared anywhere inside the function.
There are a few ways to solve these issues (the warning, naming, and scope issue) I'll let you puzzle them out first. Come back if you get stuck :)
sixstorm
Oct 3, 2006, 08:48 PM
Remember you will spend around 20% coding, and 80% debugging. So stare at your code for a little bit, and scream out some obscentity, and you will eventually get it. Worked for me. :D
By the way, your function call, its suppose to be (int, double, double, double) or make quanBreak an int instead of a double.
Haha. Let me drop this here:
double calcDiscount (int quantity, double costEach, double discountPerCent, int orderMoreThan);
int main()
{
double breakfast = 5.50;
double bDiscount = .10;
double quanBreak = 10;
int breakfastMeals;
cout << "Enter the number of meals: " << endl;
cin >> breakfastMeals;
breakfastTotal = calcDiscount (breakfastMeals, breakfast, bDiscount, quanBreak);
cout << "Your total is: " << breakfastTotal;
return 0;
}
double calcDiscount (int quantity, double costEach, double discountPerCent, double orderMoreThan)
FUNCTION
It's having a problem in the function call, saying that it has a warning assignment to 'int' from 'double'. All of my parameters are in order . . .
sixstorm
Oct 3, 2006, 08:53 PM
Also you are typing to use the variable bDiscount in your function; the way that you currently have it set up you function cannot see this variable to use it since it is not declared anywhere inside the function.
So bDiscount, an identifier, HAS to be within the function? That kinda doesn't make sense because you would want the function to use whatever is in the Main section right?
Heath
Oct 3, 2006, 09:00 PM
So bDiscount, an identifier, HAS to be within the function? That kinda doesn't make sense because you would want the function to use whatever is in the Main section right?
If you want to access it then it either has to be inside the function, or globally accessable.
I'll attempt to steer you away from global variables now however. :)
One thing you might notice if you stare at the code, is that you are not using bDiscount anywhere in main, other than to pass it to your function. You could consider moving it inside the function altogether.
Also you are passing in the value of bDiscount using discountPerCent, but trying to use bDiscount instead, I'm not sure why, but that is another thing you might want to look at.
sixstorm
Oct 3, 2006, 09:17 PM
If you want to access it then it either has to be inside the function, or globally accessable.
I'll attempt to steer you away from global variables now however. :)
One thing you might notice if you stare at the code, is that you are not using bDiscount anywhere in main, other than to pass it to your function. You could consider moving it inside the function altogether.
Also you are passing in the value of bDiscount using discountPerCent, but trying to use bDiscount instead, I'm not sure why, but that is another thing you might want to look at.
In this project, it is instructed to have the declaration as it is already, so I gotta work around that. I've made breakfast=5.50, bDiscount and breakQuan constants . . . but that doesnt help. Hope I'm making sense. How much harder would it be to make it globally accessible? Identify it before int main()?
Heath
Oct 3, 2006, 09:25 PM
In this project, it is instructed to have the declaration as it is already, so I gotta work around that. I've made breakfast=5.50, bDiscount and breakQuan constants . . . but that doesnt help. Hope I'm making sense. How much harder would it be to make it globally accessible? Identify it before int main()?
I would suggest you simply change the function line that says:
discountAmt = totalOne * bDiscount;
to use the value you have passed in instead of trying to use the bDiscount variable. You have already passed in the value, you just need to use it.
bousozoku
Oct 3, 2006, 09:25 PM
Did you clean up the costEach/eachCost misspelling?
After that and making sure the semicolons were only where they should be, it's able to be compiled and runs.
sixstorm
Oct 3, 2006, 09:45 PM
Did you clean up the costEach/eachCost misspelling?
After that and making sure the semicolons were only where they should be, it's able to be compiled and runs.
Yeah, I cleaned that up. I also changed one thing in the function, yet I'm still getting warnings/problems in the function call. If it's just one or two stupid semicolons, I'm going to freak out.
YoNeX
Oct 3, 2006, 10:07 PM
#include <iostream>
using namespace std;
//Constants
const double BREAKFAST = 5.5;
const double BDISCOUNT = 0.1;
const double QUANBREAK = 10;
double calcDiscount(int quantity, double costEach, double discountPerCent,
double orderMoreThan);
int main()
{
double breakfastTotal;
int breakfastMeals;
cout << "Enter the number of Breakfast Meals ordered: ";
cin >> breakfastMeals;
breakfastTotal = calcDiscount(breakfastMeals, BREAKFAST, BDISCOUNT,
QUANBREAK);
cout << "Your total is: " << breakfastTotal << endl;
return 0;
}
double calcDiscount(int quantity, double costEach, double discountPerCent,
double orderMoreThan)
{
double discountAmt, totalOne, subTotal;
totalOne = quantity * costEach;
if(quantity >= orderMoreThan)
{
return (totalOne - (totalOne * BDISCOUNT));
}
return (totalOne * BDISCOUNT);
}
Slightly optimized. Should work, but haven't ran it through a compiler.:o
uaaerospace
Oct 3, 2006, 10:20 PM
It's having a problem in the function call, saying that it has a warning assignment to 'int' from 'double'. All of my parameters are in order . . .
The problem is that in the function declaration you have the last variable set as one type and in the function definition you have the last variable set as another type. Those types must agree!
Think about the warning being given by the compiler. That warning actually tells you EXACTLY what is wrong with your code.
uaaerospace
Oct 3, 2006, 10:28 PM
I'll attempt to steer you away from global variables now however. :)
I second that attempt. :cool:
"With great power comes great responsibility"
Don't open yourself for additional careless mistakes. Know what you are doing and why you are doing it.
sixstorm
Oct 3, 2006, 10:29 PM
Slightly optimized. Should work, but haven't ran it through a compiler.:o
Works on XCode with 1 warning but the Linux server that I remotely access is still having the same problems as before with the 'int' to 'double' crap. :mad:
EDIT: I angrily retyped the entire thing and viola, I got it to compile. I think one thing is where I put my constants, making orderMoreThan a double instead of a constant (weird) and prolly a stroke of luck. Now onto the other parts of the program! Thanks a lot guys, this means a lot.
uaaerospace
Oct 3, 2006, 10:39 PM
Works on XCode with 1 warning but the Linux server that I remotely access is still having the same problems as before with the 'int' to 'double' crap. :mad:
There are 2 warnings in Xcode....both involve unused variables.
Can you post the code from the Linux server so that we can see what you have fixed and what remains? It would also be helpful to know the exact message from the Linux compiler and the referenced line number.
Heath
Oct 3, 2006, 10:40 PM
Works on XCode with 1 warning but the Linux server that I remotely access is still having the same problems as before with the 'int' to 'double' crap. :mad:
And it will until it's fixed. :)
Double (ha ha) check your argument types against what you pass in, try to rely on the compiler to do as little converting as you can. Even better would be to make the types match, and where you cannot, explicitly state your intentions with a cast to the appropriate type. That way later on when you revisit the code you'll know that a conversion is being done on purpose and which types are involved.
Once you get it compiling, there are a couple other things you might want to look into. One is that your breakast price total is not being totalled correctly.
When you run it then number you get back on the screen is the discount, not the total cost. Also, when you type in the number of meals, there is no checking done on the input to make sure it is in fact a number. I'm not sure how far along you are in learning so that might be a bit beyond where you sit now.
However, the one check you should always do when writing functions is to make sure that what you get passed in is what you expect. Always try to check your passed in function arguments to make sure they are valid. In your example I could type in -5 for the number of meals and the function would give a nonsensical (in this context) answer. In your case one check could be that all the arguments are greater than 0.
gnasher729
Oct 4, 2006, 04:00 AM
If I'm not being a PITA for ya, could you explain why I wouldn't put it there? Just trying to learn . . .
What kind of statements are there?
There are expression statements.
There are compound statements.
There are if, do/while, while, for, switch, goto and return statements.
And there are empty statements.
Please describe exactly what an empty statement looks like, and where you used one in your code, and why you most definitely didn't want to use it where you used it.
sixstorm
Oct 4, 2006, 07:58 AM
What kind of statements are there?
There are expression statements.
There are compound statements.
There are if, do/while, while, for, switch, goto and return statements.
And there are empty statements.
Please describe exactly what an empty statement looks like, and where you used one in your code, and why you most definitely didn't want to use it where you used it.
While I'm not that advanced yet, I still have a little trouble with my syntaxes. I'm going to start back on this project again this afternoon, so keep an eye out on this thread. I'm sure I'll have another couple of questions. Thanks guys!
sixstorm
Oct 4, 2006, 04:39 PM
Hello again. Got one quick Q, here is the code:
#include <iostream>
using namespace std;
//Constants
const double BREAKFAST = 5.5;
const double BDISCOUNT = 0.1;
const double QUANBREAK = 10;
const double LUNCH = 9.5;
const double LDISCOUNT = .15;
const double QUANLUN = 15;
const double DINNER = 16.5;
const double DINDISCOUNT = .12;
const double QUANDIN = 8;
double basicTotal, basicDiscount, costAfterDiscount;
double calcDiscount(int quantity, double costEach, double discountPerCent,
double orderMoreThan);
int main()
{
double breakfastTotal, lunchTotal, dinnerTotal;
int breakfastMeals, lunchMeals, dinnerMeals;
cout << "Enter the number of Breakfast Meals ordered: ";
cin >> breakfastMeals;
breakfastTotal = calcDiscount(breakfastMeals, BREAKFAST, BDISCOUNT,
QUANBREAK);
cout << "Enter the number of Lunch Meals ordered: ";
cin >> lunchMeals;
lunchTotal = calcDiscount(lunchMeals, LUNCH, LDISCOUNT, QUANLUN);
cout << "Enter the number of Dinner Meals ordered: ";
cin >> dinnerMeals;
dinnerTotal = calcDiscount(dinnerMeals, DINNER, DINDISCOUNT, QUANDIN);
cout << "Your breakfast total is: " << breakfastTotal << endl;
cout << "Your lunch total is: " << lunchTotal << endl;
cout << "Your dinner total is: " << dinnerTotal << endl;
return 0;
}
double calcDiscount(int quantity, double costEach, double discountPerCent,
double orderMoreThan)
{
basicTotal = quantity * costEach;
if(quantity >= orderMoreThan)
{
basicDiscount = basicTotal * discountPerCent;
costAfterDiscount = basicTotal - basicDiscount;
return costAfterDiscount;
}
return basicTotal;
}
The outcome of this program needs to display the total before discount, how much is saved (total - discount) and the total after the discount. Since the user is going to input the quantity and run it through a function, can there be more than one thing returned? Also, in this project, I can only have that calcDiscount function, no other functions can be used. How can I get it to where I can display these numbers within my main()? For example:
Total Before Discount = $xx.xx
Discount = $xx.xx
Total After Discount = $xx.xx
Heath
Oct 4, 2006, 06:38 PM
Hello again. Got one quick Q, here is the code:
The outcome of this program needs to display the total before discount, how much is saved (total - discount) and the total after the discount. Since the user is going to input the quantity and run it through a function, can there be more than one thing returned? Also, in this project, I can only have that calcDiscount function, no other functions can be used. How can I get it to where I can display these numbers within my main()? For example:
Total Before Discount = $xx.xx
Discount = $xx.xx
Total After Discount = $xx.xx
Ok, maybe I'm missing something, but couldn't you just go:
cout << "Total Before Discount = $" << // Total before discount calculation here << endl;
cout << "Discount = $" << // discount amount here
cout << "Total After Discount = $" << // Other total here
For each meal type?
This would be better siuted to go into some function, but if you are not allowed to have other functions this seems like the simplest approach.
sixstorm
Oct 4, 2006, 06:59 PM
Ok, maybe I'm missing something, but couldn't you just go:
cout << "Total Before Discount = $" << // Total before discount calculation here << endl;
cout << "Discount = $" << // discount amount here
cout << "Total After Discount = $" << // Other total here
For each meal type?
This would be better siuted to go into some function, but if you are not allowed to have other functions this seems like the simplest approach.
EDIT: NM, I figured it out. Just after doing the function, I put breakfastDiscount = basicDiscount. This takes that temporary memory cell (right after running breakfastMeals through the function) and displays it!!! At least I figured something of this out myself lol.
Heath
Oct 4, 2006, 07:10 PM
There has got to be an easier/better way to do that. If you are getting a number through your function, you should be able to display or call back that number right? If you do as you suggests, you are basically doing the function all over again in your main().
Oh I agree that it's most definitely not the way you should approach the problem. However if you are only allowed to have one function then your options become limited. A function however should ideally be short, easy to read and only do one thing. The function you have has a name of calcDiscount, to me that implies that is exactly what the function should do. No more and no less. If you start trying to cram other logic in there you head on down the trail of 'spaghetti code' and you don't want to go there. As for simpilcity.. well it can't get much simpler than that you already have the numbers, you just need to print them out basically.
YoNeX
Oct 4, 2006, 08:38 PM
Yes, when starting off, I highly suggest making more functions that do simple task, rather than a function that does a lot of stuff. Sure, it may be more inefficent and not optimized, but you are trying to learn. But once you get better at it, then you can start optimizing your code, and using little tricks. Until then, try using more functions to do your task, because debugging optimized code is a pain at times.
sixstorm
Oct 4, 2006, 10:24 PM
Well, I'm finally done with the project, thanks to your help (all of you). Keep this thread open . . . the semester isn't over yet!!! :D :D :D
sixstorm
Oct 24, 2006, 03:49 PM
Here's another problem from yours truely. It keeps telling me that calcComm can't be used as a function . . . but somehow I've got the right syntax for it. Well heck, I prolly don't since it's not working huh? Here's the code:
/*
* Pass6
*/
/* People get paid a base salary, plus a percentage of all sales over the base sales amount.
1) Read 3 digit salesman ID number, a float base salary and sales amount for each category.
2) Using a function, compute the commission earned in each category.
3) Print the ID number and base salary.
4) For each category, print description, sales amount, and commission amount.
5) Print total commission paid to the employee and total paid.
6) Continue looping until -999 is inputted for Salesman Number.
*/
#include <iostream>
#include <iomanip>
using namespace std;
/* Universal Floats */
float totalPcCom, totalMemCom, totalZipCom, totalPrintCom, baseSalary, pcSales, memCardSales, zipDriveSales, printerSales, totalCommission;
/* Function Prototype */
double calcComm(pcSales, memCardSales, zipDriveSales, printerSales);
int main ()
{
/* Everything has to be in a loop!!!! */
int salesID;
do
{
/* Output for 3 digit salesman ID number, float base salary and sales amount for each category. */
cout << "Please Enter Salesman ID number or -999 to terminate: " << endl;
cin >> salesID;
cout << "Please Enter Base Salary: " << endl;
cin >> baseSalary;
cout << "Please Enter Personal Computer Sales: " << endl;
cin >> pcSales;
cout << "Please Enter Memory Card Sales: " << endl;
cin >> memCardSales;
cout << "Please Enter Zip Drive Sales: " << endl;
cin >> zipDriveSales;
cout << "Please Enter Printer Sales: " << endl;
cin >> printerSales;
/* Function and Computation Time!!! */
totalCommission = calcComm (pcSales, memCardSales, zipDriveSales, printerSales);
/* Displaying the information for the current salesman */
cout << "Saleman ID # " << salesID << endl;
cout << "Base Salary: " << baseSalary << endl;
cout << "Total PC Commission: " << totalPcCom << endl;
}
/* Checking again if id!=-999 */
while (salesID!=-999);
return 0;
}
double calcCommission (baseSalary, pcSales, memCardSales, zipDriveSales, printerSales)
{
/* Check and see if salesman gets commission from PCs
If so, commission is calculated. If not, commission
is left at zero. */
if (pcSales>=4000)
return totalPcCom = (pcSales - 4000) * .10;
else
return totalPcCom = 0;
/* Check and see about other commissions */
if (memCardSales>=1000)
return totalMemCom = (memCardSales - 1000) * .05;
else
return totalMemCom = 0;
if (zipDriveSales>=800)
return totalZipCom = (zipDriveSales - 800) * .04;
else
return totalZipCom = 0;
if (printerSales>=2000)
return totalPrintCom = (printerSales - 2000) * .08;
else
return totalPrintCom = 0;
}
bousozoku
Oct 24, 2006, 04:19 PM
You seem to be wanting to calculate all of the commissions at once by collecting the information prior to calling the function but you're using return, which escapes the rest of the function.
You could either create separate functions for each type of commission so that you return the proper value for each or you could remove return and use pointers to allow the values to be inserted into the original variables.
Kaliemon
Oct 24, 2006, 05:09 PM
The way your functions are defined is invalid. The variables need to be defined when being used as parameters for the function. Also your check for the Sale ID only implemented after the first time the loop ran. Here is modified version of your code that is working. I added a few comments where the changes are not very drastic.
/*
* Pass6
*/
/* People get paid a base salary, plus a percentage of all sales over the base sales amount.
1) Read 3 digit salesman ID number, a float base salary and sales amount for each category.
2) Using a function, compute the commission earned in each category.
3) Print the ID number and base salary.
4) For each category, print description, sales amount, and commission amount.
5) Print total commission paid to the employee and total paid.
6) Continue looping until -999 is inputted for Salesman Number.
*/
#include <iostream>
#include <iomanip>
using namespace std;
/* Universal Floats */
float totalPcCom, totalMemCom, totalZipCom, totalPrintCom, baseSalary, pcSales, memCardSales, zipDriveSales, printerSales, totalCommission;
/* Function Prototype */
// No need for the line below as it is handled by the next function.
//double calcComm(float pcSales, float memCardSales, float zipDriveSales, float printerSales);
double calcCommission (float pcSales, float memCardSales, float zipDriveSales, float printerSales)
{
/* Check and see if salesman gets commission from PCs*
If so, commission is calculated. If not, commission
is left at zero. */
if (pcSales>=4000)
totalPcCom = (pcSales - 4000) * .10;
else
totalPcCom = 0;
/* Check and see about other commissions */
if (memCardSales>=1000)
totalMemCom = (memCardSales - 1000) * .05;
else
totalMemCom = 0;
if (zipDriveSales>=800)
totalZipCom = (zipDriveSales - 800) * .04;
else
totalZipCom = 0;
if (printerSales>=2000)
totalPrintCom = (printerSales - 2000) * .08;
else
totalPrintCom = 0;
return (totalPcCom, totalMemCom, totalZipCom, totalPrintCom);
}
int main ()
{
/* Everything has to be in a loop!!!! */
int salesID;
do
{
/* Output for 3 digit salesman ID number, float base salary and sales amount for each category. */
cout << "Please Enter Salesman ID number or -999 to terminate: " << endl;
cin >> salesID;
if (salesID == -999)
break;
cout << "Please Enter Base Salary: " << endl;
cin >> baseSalary;
cout << "Please Enter Personal Computer Sales: " << endl;
cin >> pcSales;
cout << "Please Enter Memory Card Sales: " << endl;
cin >> memCardSales;
cout << "Please Enter Zip Drive Sales: " << endl;
cin >> zipDriveSales;
cout << "Please Enter Printer Sales: " << endl;
cin >> printerSales;
/* Function and Computation Time!!! */
//Call the calcCommission function instead of calcComm
totalCommission = calcCommission (pcSales, memCardSales, zipDriveSales, printerSales);
/* Displaying the information for the current salesman */
cout << "Saleman ID # " << salesID << endl;
cout << "Base Salary: " << baseSalary << endl;
cout << "Total PC Commission: " << totalPcCom << endl;
}
/* Checking again if id!=-999 */
while (salesID!=-999);
}
sixstorm
Nov 1, 2006, 08:39 PM
Thanks for the replies everyone. Sorry I haven't responded quicker. Here is another one for ya. I'm writing a program that basically displays a menu (see menu function) and the user has to select one letter from the menu. On whichever letter is selected, it will access a function. Here is the code:
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototypes
void bestbuy(float val1, float val2, float val3);
void discountresults(float price, float discount);
void howmany(float amount, float costperitem);
void menu(string selection);
int main()
{
string selection;
float val1, val2, val3, price, discount, amount, costperitem;
// Bring up Menu from menu function
menu(selection);
// While "q" is not selected . . .
while(selection!="q")
{
cin >> selection;
if(selection=="b")
bestbuy(val1, val2, val3);
else if(selection=="d")
discountresults(price, discount);
else if(selection=="h")
howmany(amount, costperitem);
else
return 0;
}
}
void menu(string selection)
{
cout << "(B)est Buy Calculation" << endl;
cout << "(D)iscount Calculation" << endl;
cout << "(H)ow Many Calculation" << endl;
cout << "(Q)uit" << endl;
cout << endl;
cout << "Please Enter The Option (B, D, H or Q): ";
}
void bestbuy(float val1, float val2, float val3)
{
float number, minimum;
cout << "Please Enter 3 Prices: ";
cin >> val1 >> val2 >> val3;
// Find minimum price
if(val1>val2&&val2<val3)
minimum = val2;
else if (val1>val3&&val3<val2)
minimum = val3;
else if (val3>val1&&val1<val2)
minimum = val1;
else
minimum = 0;
// Find number of price
if(minimum==val1)
number = 1;
else if(minimum==val2)
number = 2;
else if(minimum==val3)
number = 3;
else
number = 0;
}
void discountresults(float price, float discount)
{
float total;
cout << "Please Enter a Price and the Discount Amount: ";
cin >> price >> discount;
total = price * (discount + 1);
cout << "The discount amount is " << discount << " the discounted price is " << total;
}
void howmany(float amount, float costperitem)
{
float amount, costperitem, numberitems, remainder;
cout << "Please Enter Amount Available and Cost of Each Item: ";
cin >> amount >> costperitem;
numberitems = amount / costperitem;
remainder = amount%costperitem;
cout << "You can buy " << numberitems << " and have " << remainder << " left over." << endl;
}
There are a few errors on here from XCode but I wanted to check with people here on a few things. Take a look at the first few lines in int main(). Will that code access the menu that's in the function? Also, does everything else look legit?
Soulstorm
Nov 2, 2006, 01:42 AM
For start, please use code tags, which formats the code and supports identation. It will be easier to read your code that way.
Secondly, see the howmany function:
void howmany(float amount, float costperitem)
{
float amount, costperitem, numberitems, remainder;
cout << "Please Enter Amount Available and Cost of Each Item: ";
cin >> amount >> costperitem;
numberitems = amount / costperitem;
remainder = amount%costperitem;
cout << "You can buy " << numberitems << " and have " << remainder << " left over." << endl;
}
Those are your errors in this function:
1) the "howmany" word is typedefed by another part of the C++ standard libraries. Don't ask me what part that is, I don't know. I just pressed the "escape" key and Xcode showed me that this word is typedef-ed. Change it to something different
2) You have declared the variables "amount" and "costperitem" twice. Why have you done that, and why do you want to 'cin' the "amount" and costperitem, since you have already passed their values as arguments to the function?
When you correct those mistakes, others will come up, you'll see. I didn't do it for you, since if I do, I will need to change the entire way you have done your exercise, and that wouldn't be appropriate. The only thing I can say is that using string comparisons just to select a function is inelegant and inefficient. it may cause you problems afterwards. I would do it with integers.
Also, a do...while loop would be best here. Define the integer outside the loop. And inside the 'do' loop, have it take a value by the user. Then, do whatever you want with it, and at the end of the loop, you should put something like '(while choice != 0)' ... That way you ensure that the statements inside the loop will at least be ran once.
sixstorm
Nov 2, 2006, 05:05 PM
Thanks for the help man. Our teacher decided to give us a hint or two and that lead to redesigning all the functions and stuff. I guess I was trying to have JUST the functions inside main() and then have the functions do the rest. Guess you can't do it that way huh? I'm debugging and tweaking right now so I'll be back I'm sure. Thanks again.
sixstorm
Nov 14, 2006, 03:38 PM
Haha, it's me again. I don't really need help with code for this one, but I just don't understand the concept of streaming information from text files. The biggest thing that I don't get is that when you have a text file filled with people's name, numbers, information, etc and you are using ifstream in a program to read from that file, how does the computer know what is what? I've got a program that will be doing exactly this; the text file has a nice layout of all the info mentioned above and I have to make a program to display all that info to the screen.
To clarify my question, let's look at cout. To display info to the monitor, you use cout right? cout << data; You tell the computer what to display very generally. If you are displaying multiple data items from a text file, how would you get specific information, such as JUST the customer's name or JUST the customer's number?
In one of my example programs, a teacher uses a program that reads from a text file which contains the number of students (header file, I know), grades from test 1 and grades from test 2. In my textbook, here is how it has the "input":
scores_in >> score1 >> score2;
Now how does the program know what test score is score 1? Score 2? This is what I'm trying to figure out. Sorry for the long post but I really needed to explain myself and see if anyone knows what I'm talking about. Any suggestions will help. Thanks!
sixstorm
Nov 14, 2006, 07:59 PM
Anybody?
sixstorm
Nov 15, 2006, 10:24 AM
Quick morning bump. I really need help understanding this concept so any kind of advice will help. Thanks in advance.
sixstorm
Nov 15, 2006, 04:56 PM
bump
steelphantom
Nov 15, 2006, 06:53 PM
In one of my example programs, a teacher uses a program that reads from a text file which contains the number of students (header file, I know), grades from test 1 and grades from test 2. In my textbook, here is how it has the "input":
scores_in >> score1 >> score2;
Now how does the program know what test score is score 1? Score 2? This is what I'm trying to figure out. Sorry for the long post but I really needed to explain myself and see if anyone knows what I'm talking about. Any suggestions will help. Thanks!
The way that this particular example works is that data values in the input stream are broken up by spaces. So, if your text file contained "75 90" in it, scores_in would read 75 for score1 and 90 for score2. That was probably a horrible explanation, but I hope it helps at least a little bit. :o
sixstorm
Nov 15, 2006, 08:18 PM
The way that this particular example works is that data values in the input stream are broken up by spaces. So, if your text file contained "75 90" in it, scores_in would read 75 for score1 and 90 for score2. That was probably a horrible explanation, but I hope it helps at least a little bit. :o
That does make sense and helps out a pretty good amount. Thanks! Any other suggestions?
sixstorm
Nov 15, 2006, 09:38 PM
Alright here is my project. Let me know what you think. I don't really have a way of testing it out but it builds just fine in XCode. Here it is:
EDIT: Sorry for the look of the format. I copied straight from XCode onto here and it changed things to make it look nasty. Sorry!
#include <iomanip>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
// Reads the following information from an external text file named "customer.dat", terminating with EOF check.
// Customer Number -> Int
// Customer Name -> String (Use getline)
// Beginning Balance -> Float
// Credit Card Charges -> Float
// Amount Paid -> Float
// Finance Charges -> Float
int customerNumber;
string customerName;
float begBal, creditCharges, amtPaid, finCharges, currentBal, howMany;
ifstream custom_in;
ofstream sum_out;
// Opens the "customer.dat" file.
custom_in.open("customer.dat");
assert(!custom_in.fail());
sum_out.open("summary.dat");
assert(!sum_out.fail());
howMany = 0;
// Display all the information to the screen, as well as current balance (beginning balance+credit card charges+
// amount paid+finanace charges).
while(!custom_in.eof())
{
// Get information from "customer.dat" and into the program.
custom_in >> customerNumber;
getline (custom_in, customerName);
custom_in >> begBal >> creditCharges >> amtPaid >> finCharges;
currentBal = begBal + creditCharges + amtPaid + finCharges;
// Total all appropriate columns and tell how many customers there were.
cout << customerNumber << " " << customerName << " " << begBal << " $" << creditCharges << " $" << amtPaid << " $" << finCharges << " $" << currentBal;
howMany += 1;
cout << "The total number of customers is " << howMany << endl;
// Create a new file "summary.dat" that contains Customer Number, Name and Current Balance.
// Writing into a new file called "summary.dat"
sum_out << customerNumber << endl;
sum_out << customerName << endl;
sum_out << currentBal << endl;
custom_in >> ws;
}
custom_in.close();
sum_out.close();
return 0;
}
LtRammstein
Nov 16, 2006, 01:39 PM
Well, for one, your howMany data will print out every time, only incremented at the end of each loop. You can also rewrite that as:
++howMany
This does howMany += 1 only it doesn't have to copy the memory slot again, or store any extra assignment operators. So, in a sense, it's faster.
Also, you split between your declared istream and ostream names. I found a cout in there that shouldn't be in there unless you want the user to see it. Even then, it should be after the while loop.
Other than that I don't see anything wrong with it.
A way to test the code is to create a .dat file in your project folder with information stored in it. Remember to not put any delimitors between data. The istream in this context:
cin >> data1 >> data2 >> data 3;
The istream already defines a space in a text file being a delimitor. If there is a deliminitor, like a semicolon, it will think it's apart of the data and continue on and then throw a run-time error.
Finally, it would look nicer if you indented your code. It hurts my eyes trying to run the code in my head and not seeing any indents.
sixstorm
Nov 16, 2006, 01:49 PM
Also, you split between your declared istream and ostream names.
What do you mean by split? I'm guessing not in the right order?
I found a cout in there that shouldn't be in there unless you want the user to see it. Even then, it should be after the while loop.
I'll take a look for that one. Everything should be shown just like it's say in the comments.
Finally, it would look nicer if you indented your code. It hurts my eyes trying to run the code in my head and not seeing any indents.
Well, I copied the stuff straight from XCode but when I clicked "Post", it automatically formatted it this way, sorry. I put a disclaimer!!! :D Thanks for your help man.
LtRammstein
Nov 16, 2006, 01:56 PM
When I mean split, you don't follow your design. You got from your declared iostream names to cout/cin. Try to watch for those.
sixstorm
Nov 30, 2006, 10:18 PM
Got the last project of the semester . . . and I have no clue about this crap. It's about arrays and vectors. Here is my code with a program explaination included. Sorry about the indentation, blame it on the message boards. I copy and paste :D
#include <iostream>
#include <iomanip>
#include <vector>
#include <fstream>
#include <string>
#include <cassert>
const int MAXSTUDENTS = 101;
void get_data(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA);
void print_out(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA);
/* This program starts out reading from an external file 'Students.dat", terminates with EOF and stores the records in 3 separate
arrays. Assume that there are up to 100 students in the file. */
/* Social Security Number (Int)
Student Name (String)
GPA (Float)
*/
/* Display everything properly with column headings IN REVERSE ORDER!!! At the end, give the total # of students and the avg GPA. */
int main ()
{
vector<int>& ssNumber(MAXSTUDENTS);
vector<string>& studentName(MAXSTUDENTS);
vector<float>& GPA(MAXSTUDENTS);
float avg;
int totalStudents;
return 0;
}
void get_data(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA)
{
ifstream students_in;
students_in.open("STUDENTS.DAT");
assert(!students_in.fail());
int size;
size = 0;
while(students_in >> ws && !students_in.eof())
{
students_in >> ssNumber[size];
getline (students_in, studentName[size]);
students_in >> GPA[size];
size++;
}
}
void print_out(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA)
{
int size;
for(i=size; i>=0; i--)
cout << ssNumber[size] << ' ';
cout endl;
}
I know there are prolly a thousand things wrong with it, but I have no idea why. I'm following syntax rules to the tee but I'm still getting errors. Thanks in advance. I actually need a response tonight cuz it's due at midnight ahhh!!! Oh well, it wouldn't hurt to turn in a crappy project, I have a good grade. But I'd still like to learn this stuff!
Xavier
Nov 30, 2006, 10:56 PM
I dunno, just look at your C++ GUI Programming Guide, that might help :)
(I know nothing about C++, but the new mac ad was funny)
SamMiller0
Dec 1, 2006, 10:01 AM
I know there are prolly a thousand things wrong with it, but I have no idea why. I'm following syntax rules to the tee but I'm still getting errors.
For starters, please post the errors you encounter when compiling. After a quick glance at your code, I noticed you will need to bring in a couple things from the std namespace:
using std::vector;
using std::ifstream
using std::cout;
using std::endl;
savar
Dec 1, 2006, 10:16 AM
hmm, well, it compiles fine with the if/else command in xCode, however the text I have on c++ mentions no such command. Also, when taking c++ classes, we always used if statements. Perhaps it's just personal preference of my professors. Oh well, I learn something new every day....this time from a self proclaimed "noob" :p :D
It's definitely a standard feature of the langauge. Any language that didn't have such a contruct would never get mainstream traction.
By the way, two if statements is different than an if-else statement, even if the two conditions in the former case are mutually exclusive and exhaustive: if-else compiles to one branch, where as "if-if" compiles to two.
You should always use if-else, never "if-if", if for no other reasons than clarity and maintainability.
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.