Having trouble cout-ing returned functions - c++

I am new to C++ and am having trouble passing string back to the main class of my code.
My goal is to split the below code so that I have 2 functions other than the main class and at least one must return a value other than 0.
Beginning code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout.precision(2);
cout.setf(ios::fixed,ios::floatfield);
float speedLimit;
float driversSpeed;
float ticketAmount;
float speedOver;
string repeat;
/*Use a symbolic constant for the base ticket fine rate ($50).*/
const float base = 50;
start:
/*Prompt the user for the speed limit and the speed of the driver.*/
cout << "Enter the speed limit: ";
cin >> speedLimit;
cout << "Enter the driver's speed: ";
cin >> driversSpeed;
cout << "You were driving " << driversSpeed << " in a " << speedLimit << " mph zone.\n";
speedOver = driversSpeed - speedLimit;
if (speedOver <= 10 && speedOver >= 1)
{
ticketAmount = base;
}
else if (speedOver <= 14 && speedOver >= 11)
{
ticketAmount = (base *.05) + base;
}
else if (speedOver <= 19 && speedOver >= 15)
{
ticketAmount = (base *.1) + base;
}
else if (speedOver <= 24 && speedOver >= 20)
{
ticketAmount = (base *.15) + base;
}
else if (speedOver <= 29 && speedOver >= 25)
{
ticketAmount = (base *.2) + base;
}
else if (speedOver >= 30)
{
ticketAmount = (base *.25) + base;
}
else
{
ticketAmount = 0;
}
cout << "Your fine is $" << ticketAmount;
cout << "\nEnter Y to continue. Anything else to stop: ";
cin >> repeat;
if (repeat == "Y" || "y")
goto start;
else
exit(0);
return 0;
}
and here what I have done so far:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const float base = 50;
float speedLimit;
float driversSpeed;
float ticketAmount;
float speedOver;
int _tmain(int argc, _TCHAR* argv[])
{
cout.precision(2);
cout.setf(ios::fixed,ios::floatfield);
string repeat;
/*Use a symbolic constant for the base ticket fine rate ($50).*/
start:
/*Prompt the user for the speed limit and the speed of the driver.*/
cout << "Enter the speed limit: ";
cin >> speedLimit;
cout << "Enter the driver's speed: ";
cin >> driversSpeed;
/*Display to the user the values which were input (speed limit and driver's speed) and the calculated ticket fine amount. Print 2 numbers after the decimal point for the fine amount. Make sure your output format matches the sample format.*/
cout << "You were driving " << driversSpeed << " in a " << speedLimit << " mph zone.\n";
speedOver = driversSpeed - speedLimit;
cout << string(finalOutput);
/*After the fine is printed for the first speeding violation, prompt the user to see if he/she wants to enter another speeding violation. If so, prompt again for the speed limit and driver's speed. Repeat the calculation and print the fine. Repeat this process until the user indicates he/she wants to stop. The user can enter either an uppercase or lowercase letter Y to continue with the program.*/
cout << "\nEnter Y to continue. Anything else to stop: ";
cin >> string(repeat);
if (repeat == "Y" || "y")
goto start;
else
exit(0);
}
float ticketAmountFunc(float ticketAmount)
{
/*Calculate the ticket cost as $50 (the base fine rate) plus:
0% additional if the driver's speed was 10 or less miles per hour above the speed limit.
5% additional if driver's speed was more than 10 miles per hour above the speed limit.
10% additional if driver's speed was more than 15 miles per hour above the speed limit
15% additional if driver's speed was more than 20 miles per hour above the speed limit.
20% additional if driver's speed was more than 25 miles per hour above the speed limit.
25% additional if driver's speed was 30 or more miles per hour above the speed limit.
Do not charge a fine if the driver wasn't speeding.*/
if (speedOver <= 10 && speedOver >= 1)
{
ticketAmount = base;
}
else if (speedOver <= 14 && speedOver >= 11)
{
ticketAmount = (base *.05) + base;
}
else if (speedOver <= 19 && speedOver >= 15)
{
ticketAmount = (base *.1) + base;
}
else if (speedOver <= 24 && speedOver >= 20)
{
ticketAmount = (base *.15) + base;
}
else if (speedOver <= 29 && speedOver >= 25)
{
ticketAmount = (base *.2) + base;
}
else if (speedOver >= 30)
{
ticketAmount = (base *.25) + base;
}
else
{
ticketAmount = 0;
}
return ticketAmount;
}
string finalOutput(string tix)
{
string words = "Your fine is $";
//tix = words + ticketAmountFunc;
tix += string(words) + string(ticketAmountFunc);
return tix;
}
VS is returning 2 errors:
Error 1 error C2065: 'finalOutput' : undeclared identifier
Error 7 error C2440: '<function-style-cast>' : cannot convert from 'float (__cdecl *)(f
loat)' to 'std::string'
Could someone please poing me in the direction of my error?
Thank you.
EDIT: Thank you Ben. I moved my main method and tried moving variables around to declare them as strings and still have the undeclared identifier issue but now twice.
Here is my updated code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const float base = 50;
float speedLimit;
float driversSpeed;
float ticketAmount;
float speedOver;
string ticketAmountFunc(string r)
{
string ticketAmount;
if (speedOver <= 10 && speedOver >= 1)
{
ticketAmount = base;
}
else if (speedOver <= 14 && speedOver >= 11)
{
ticketAmount = (base *.05) + base;
}
else if (speedOver <= 19 && speedOver >= 15)
{
ticketAmount = (base *.1) + base;
}
else if (speedOver <= 24 && speedOver >= 20)
{
ticketAmount = (base *.15) + base;
}
else if (speedOver <= 29 && speedOver >= 25)
{
ticketAmount = (base *.2) + base;
}
else if (speedOver >= 30)
{
ticketAmount = (base *.25) + base;
}
else
{
ticketAmount = "0";
}
std::string s = ticketAmount;
r = s;
return r;
}
string finalOutput(string tix)
{
string words = "Your fine is $";
//tix = words + ticketAmountFunc;
tix = string() + words + ticketAmountFunc(r);
return tix;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout.precision(2);
cout.setf(ios::fixed,ios::floatfield);
string repeat;
/*Use a symbolic constant for the base ticket fine rate ($50).*/
start:
/*Prompt the user for the speed limit and the speed of the driver.*/
cout << "Enter the speed limit: ";
cin >> speedLimit;
cout << "Enter the driver's speed: ";
cin >> driversSpeed;
cout << "You were driving " << driversSpeed << " in a " << speedLimit << " mph zone.\n";
speedOver = driversSpeed - speedLimit;
cout << string(finalOutput(tix));
cout << "\nEnter Y to continue. Anything else to stop: ";
cin >> string(repeat);
if (repeat == "Y" || "y")
goto start;
else
exit(0);
}
and my errors are:
Error 7 error C2065: 'r' : undeclared identifier
Error 8 error C2065: 'tix' : undeclared identifier

You're trying to use the functions before their "point of declaration". There are two simple solutions (pick one):
Add a forward declaration aka prototype before you use it.
Move the caller (main()) below the functions it uses.
Also, when calling a function, you need to provide its arguments inside parentheses. So you need to say ticketAmountFunc(ticketAmount) and not just ticketAmountFunc.
In addition to these problems, you seem to be defining function parameters as the value the function generates, instead of the data it uses. That's not useful. When you use functions well, you won't need global variables.

If I could just add, try to avoid using goto statements at this stage in your career - make use of proper loops and functions instead.
This is not a blanket rule, but goto's can be avoided unless there are very specific & valid reasons.
You could use loops like this:
bool Quit = false;
while(!Quit) {
// user wants to quit
Quit = true; // execution continues after end of while loop
}
Also make use of the toupper function, google "C++ toupper" so that you don't have to do 2 test on the value of the char.
If you can, avoid using namespace std as it pollutes the gloabal namespace which can cause conflict with function & variable names. For example the STL has all kinds of common words like distance, left & right etc which have special meaning. So either put std:: before each std thing, or do this for frequently used things:
using std::cout;
using std::cin;
using std::endl;
using std::string;
Some guys use std:: exclusivley, while I sometimes do a mixture of these two ideas.
Hope all goes well.

Related

GPA rater in C++

I'm trying to code a GPA rater.
The problem:
Write a C++ program that asks the user for their cumulative GPA in the range [0,4]. If the GPAenter code here
is in:
[3-4] you say, “Superb!”
[2-3[ you say, “Good!”
[1-2[ you say, “Hmm!”
[0-1[ you say, “No comment!”
The program should display an error message and exit if the GPA entered exceeds 4 or less than
0.
Code:
#include <iostream>
using namespace std;
int main()
{
double grade;
cout << "Input your GPA: ";
cin >> grade;
cout << endl << endl;
if (grade >= 0 && grade <= 4)
{
if (grade >= 0 && grade <= 1)
{
cout << "No comment!";
}
if (grade >= 1 && grade <= 2)
{
cout << "Hmm!";
}
if (grade >= 2 && grade <= 3)
{
cout << "Good!";
}
if (grade >= 3 && grade <= 4)
{
cout << "Superb!";
}
}
else
{
cout << "Error : GPA is not in the specified range";
}
return 0;
}
I feel there is a more efficient way than mine.
Is there?
Thanks in advance
There's probably a way to code golf it, but your code is clear. It does check things that you already know more than once.
For example, if (grade >= 0), then it still is on the next line. If it's not <= 1, then it is definitely > 1 -- you only need to check if it's <= 2 (with else if).
If you want to make something silly, you could something like this (after checking if grade is in range):
string m[4] = {"No comment!", "Hmm!", "Good!", "Superb!"};
cout << m[min(3, int(grade))];
You need to add:
#include <cmath>
#include <string>
It's fewer lines of code, but possibly not more efficient (you need to measure)

C++ User-Defined Function Variable Won't Change From 0 [duplicate]

This question already has answers here:
Why does dividing two int not yield the right value when assigned to double?
(10 answers)
Closed 7 months ago.
I've been working on problems out of D.S. Malik C++ Programming book and I'm not looking for an answer but an explanation as to why in my charges function does billingAmount return 0 for incomeLow (Line 135). If I answer 70 for hourly rate, 15000 for customers income, and 75 for consulting time I should get $21.00
(70 * 40 * (45 / 60)) = $21.00
45 comes from subtracting 30 from 75 minutes since anything less than 30 minutes charges are free (0).
#include <iostream>
#include <iomanip>
using namespace std;
// Declared function identifiers
bool check_number(string str);
double hourly_rate();
double customer_income();
int consult_time();
double charges(double revenue, double rate, int time, bool incomeLow);
string tempRate;
string tempIncome;
string tempConsultTime;
int main()
{
int income = 0;
int consultTime = 0;
double hourlyRate = 0;
bool lowIncome = false;
hourlyRate = hourly_rate();
while (income <= 0)
{
income = customer_income();
}
if (income <= 25000) {
lowIncome = true;
}
consultTime = consult_time();
cout << fixed << showpoint << setprecision(2);
cout << "Billing Amount: "
<< charges(income, hourlyRate, consultTime, lowIncome)
<< "Low Income: " << lowIncome;
return 0;
}
bool check_number(string str) {
for (int i = 0; i < str.length(); i++) {
if (!isdigit(str[i])){
if (str[i] == '-'){
return false;
}
if (str[i] == '.'){
return true;
}
return false;
}
}
return true;
}
double hourly_rate()
{
cout << "Enter the hourly rate or 'n' to exit: ";
cin >> tempRate;
while(!check_number(tempRate))
{
if (tempRate[0] == 'n')
{
exit(0);
}
cout << "Error: Enter a positive hourly rate or 'n' to exit: ";
cin >> tempRate;
}
return stod(tempRate);
}
double customer_income()
{
cout << "Enter customers income or 'n' to exit: ";
cin >> tempIncome;
while(!check_number(tempIncome) || tempIncome == "0")
{
if (tempIncome[0] == 'n')
{
exit(0);
}
cout << "Error: Enter a positive integer or 'n' to exit: ";
cin >> tempIncome;
}
return stod(tempIncome);
}
int consult_time()
{
cout << "Enter the amount of consulting time (in minutes): ";
cin >> tempConsultTime;
while(!check_number(tempConsultTime))
{
if (tempConsultTime[0] == 'n')
{
exit(0);
}
cout << "Error: Enter a positive consult time (in minutes) or 'n' to exit: ";
cin >> tempConsultTime;
}
return stoi(tempConsultTime);
}
double charges(double revenue, double rate, int time, bool incomeLow){
double billingAmount;
int T;
if (incomeLow) {
if (revenue <= 25000 && time <= 30)
{
return 0;
} else if (revenue <= 25000 && time > 30) {
T = time - 30;
billingAmount = rate * 40 * (T / 60);
}
}
if (!incomeLow && time <= 20) {
return 0;
} else {
T = time - 30;
billingAmount = rate * 70 * (T / 60);
}
return billingAmount;
}
You obviously think that (45 / 60) is 0.75. In ordinary math it would be, but in C++ this is integer division and the result is always an integer (truncated towards zero). In effect 0.75 is rounded down to 0.
Just change (T / 60) to (T / 60.0) and you are no longer doing integer division and the result will be 0.75.

Conditonals using c++

I am coding a simple speeding ticket program and I got it to compile but I am having problems getting it to read my conditions and execute the final part of the program which is calculating the ticket.
#include <iostream>
using namespace std;
int main()
{
int speedTraveled;
int speedLimit = 55;
int mischiefSpeed = 75;
int criminalSpeed = 110;
cout << "How fast were you going? " << "\n";
cin >> speedTraveled;
if (speedTraveled >= 0 || speedTraveled >= 150)
{
if (speedTraveled > speedLimit && speedTraveled > mischiefSpeed)
{
int tFormula = ((speedTraveled - speedLimit) * 2) + 50;
cout << "You were speed bettween 55mph - 75mph your fine is : ", tFormula, '\n';
}
else if (speedTraveled > mischiefSpeed && speedTraveled < 110)
{
int tFormula = ((speedTraveled - speedLimit) * 5) + 50;
cout << "Your speed was over 75 mph but less than 110 mph your are being arrested : ", tFormula, '\n';
}
else if (speedTraveled >= criminalSpeed)
{
int tFormula = ((speedTraveled - speedLimit) * 2) + 50;
cout << "You were speed over 110 mph your are being arrested : ", tFormula, '\n';
}
}
return 0;
}
I tested using the value 150. The first if statement executes because you did not set an upper bound on it. Try setting the second > into a <. Same thing with the first if statement
if (speedTraveled >= 0 || speedTraveled >= 150) // No upper bound
if (speedTraveled >= 0 || speedTraveled <= 150) // Upper bound is 150
The fine amounts are not printing because you need an insertion operator (<<) between the different data types you are trying to output. cout uses syntax different from output functions in other languages.
cout << "You were speed between 55mph - 75mph your fine is : ", tFormula, '\n';
cout << "You were speed between 55mph - 75mph your fine is : " << tFormula << endl;
You have more if statement typos, but I'm sure you can find the rest.

Need help defining a Loop Control Variable (while loops) C++

I have been trying forever to figure out what loop control variable (LCV) to use for my program to work but I have been unsuccessful.
The information given is as follows:
You will be promoting a student for grades and credits for courses taken. From that, you will calculate a GPA.
The course name is prompted for, but nothing is done with it.
We are just using the grades A, B, C, D, and F so you won't have to do so much typing!
You will need to use the "set precision" command as shown in the book. Set it to "fixed" and "2".
You will need to use the "cin.ignore()" function as discussed earlier in the course.
Notes
I used int total to count the number of classes.
Current while statement was my last attempt, and it is not correct.
My code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main () {
cout << std::fixed << std::setprecision(2);
string course, grade, answer;
int credits, total = 0;
float gradePoints = 0, totalCredits = 0;
float gpa = 0.0;
while (grade <= "ABC") {
cout << "Enter a course name: ";
getline(cin, course);
cout << course << endl;
cout << "Enter number of credits: ";
cin >> credits;
cout << credits << endl;
cout << "Enter your grade (A, B, C, D, F): ";
cin >> grade;
cout << grade << endl;
cout << "Continue ('Yes' or 'No')? ";
cin >> answer;
cout << answer << endl;
if (grade == "A") {
gradePoints = gradePoints + 4;
}
else if (grade == "B") {
gradePoints == gradePoints + 3;
}
else if (grade == "C") {
gradePoints = gradePoints + 2;
}
else if (grade == "D") {
gradePoints = gradePoints + 1;
}
else if (grade == "F") {
gradePoints = 0;
}
total = total + 1;
totalCredits = totalCredits + credits;
}
gpa = (total * gradePoints)/ totalCredits;
return 0;
}
Based on the way the rest of the program is written, I'd think that you'd want to check against the user's response to the "Continue?" question. Something like this:
bool answer = true;
while (answer) {
// code
// when ready to exit...
answer = false;
}
That said, it might make more sense to use a do-while loop, where the first block executes before the conditional is checked:
do {
// code
} while (answer != "No");
And while you're at it, you might also want to consider using a different flag than having the user type in "Yes" or "No". Something like y and n is more common and a bit simpler.
"while (grade <= "ABC")"
If the intent is to say only do the loop while grade has a value of A, or B, or C, then:
while(grade == "A" || grade == "B" || grade == "C")

C++ if/else statements not properly outputting

currently, I am having an issue with this if/else statement. this is the source here:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
string firstname, secondname;
const int A_SCORE = 90;
const int B_SCORE = 80;
const int C_SCORE = 70;
const int D_SCORE = 60;
int testscore1;
int testscore2;
int testscore3;
int testscore4;
int testscore5;
int testscore6;
int testscore7;
int testscore8;
int testscore9;
int testscore10;
cout << "Enter your 10 scores and I will average\n"
<< "the total score, and assign letter grades" << endl;
cin >> testscore1;
cin.ignore();
cin >> testscore2;
cin.ignore();
cin >> testscore3;
cin.ignore();
cin >> testscore4;
cin.ignore();
cin >> testscore5;
cin.ignore();
cin >> testscore6;
cin.ignore();
cin >> testscore7;
cin.ignore();
cin >> testscore8;
cin.ignore();
cin >> testscore9;
cin.ignore();
cin >> testscore10;
cin.ignore();
int sum = testscore1 + testscore2 + testscore3 + testscore4 + testscore5 + testscore6 + testscore7 + testscore8 + testscore9 + testscore10;
int average = sum / 10;
if (average == 90);
{
cout << "your average is an A.";
}
else if (average == 80);
{
cout << "you have an average of a B.";
}
else if (average == 70);
{
cout << "you have an average of a C.";
}
else (average == 60);
{
cout << "your average is a D.":
}
system("pause");
return 0;
}
what the goal of this homework assignment is, is to input 10 numerical grades and have an average print out to screen with a letter grade based on average of the 10 grades. I no matter what I input, I always get 'your grade is an A. I have went over my notes ad well as looking to goodle/StackOverflow for what could be wrong. I also get compile errors too, which I cannot figure out. If someone could give me any ideas on what could be causing the issue, I would greatly appreciate it!
Remove the semicolons after the if statements and instead of checking for the values to be exactly 90/80/70 try something like this:
if(average >= 90)
{
//print
}
If you want more accurate results try using floats instead of integers.
Your if-statements should take the form of if(average >= 90, 80, etc...).
Also, what are your errors?
EDIT:
if (average >= 90)
{
cout << "your average is an A.";
}
else if (average >= 80)
{
cout << "you have an average of a B.";
}
else if (average >= 70)
{
cout << "you have an average of a C.";
}
else if(average >= 60)
{
cout << "your average is a D.";
}
else
{
cout << "your average is an F.";
}
return 0;
You needed to remove all of the semicolons, one colon, change your relational operator from == to >=, and add an extra else to catch anything below 60.
If..else statements are conditional. You need to provide the accurate conditions to get the results that you expect.
Try:
if (average >= A_SCORE)
{
cout << "your average is an A.";
}
else if (average >= B_SCORE)
{
cout << "you have an average of a B.";
}
else if (average >= C_SCORE)
{
cout << "you have an average of a C.";
}
else if(average >= D_SCORE)
{
cout << "your average is a D.";
}
else
{
cout << "your average is an F.";
}
system("pause);