I've been having trouble doing this assignment. I'm just having a hard time understanding and I am not entirely sure what to do. I've researched and watched videos and havent been able to find the right, specific information. Its a bunch of questions, so I hope someone can not only giveme the answers, but also explain to me so I have a strong understanding :) . Here are the questions:
1)In this exercise we have been given some program code that will accept two integers as inputs
and evaluate which one holds the larger value. This evaluation occurs in multiple places
throughout the code. Write a function that the program could use to perform this same evaluation
instead of duplicating the code over and over. Start by writing a suitable function declaration
towards the beginning of the code file. You will have to decide whether your function will return
some output or not.
2) With your declaration written proceed to define the function, including the appropriate pieces of
code that will evaluate which of the two integers is the largest. If you stated earlier that your
function will return a value, be sure to define what it will return here.
3) Use your result from parts (1) and (2) to reduce the amount of duplicate code in the main function
provided by replacing the multiple instances of the integer comparison with a call to invoke the
function you have created. Remember that the function will require two integers to be passed in
as arguments and if you are returning some value from the function it should be used (stored in
a variable, outputted to screen, etc.). As a word of advice, test your function works correctly after
replacing just one of the evaluations, don’t replace them all at once (if the function works correctly
for the first replacement then it should work for the others).
4) Since the function you have created only compares the values of its parameters and doesn’t write
to them (i.e. change the value stored in them) we should specify in the function declaration and
definition that these parameters should be treated like constants. Make the necessary
modifications to the function and test again to verify the function still works. Confirm the function
will not let you change the data of the parameters by trying to include an operation in the function
that would change the value of one of the variables (e.g. number2 += 10;)
-- Here is the code ( I apologise for the long writing):
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
int nNum1 = 10, nNum2 = 11;
cout << "This program will compare two numbers and report which one is larger.\n\n"
<< "Proceeding with evaluation...\n" << endl;
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int numberA = 234;
int numberB = 234;
cout << "\nUsing numbers: " << numberA << " and " << numberB << ", the larger one is: ";
if (numberA > numberB)
cout << numberA << endl;
else if (numberA < numberB)
cout << numberB << endl;
else
cout << "Neither of them! It's a draw." << endl;
int one = 'a';
int two = 'A';
cout << "\nUsing numbers: " << one << " and " << two << ", the larger one is: ";
if (one > two)
cout << one << endl;
else if (one < two)
cout << two << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\nUsing numbers: " << 13 << " and " << 84 << ", the larger one is: ";
if (13 > 84)
cout << 13 << endl;
else if (13 < 84)
cout << 84 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int input1 = 0;
int input2 = 0;
cout << "\nPlease enter a number: ";
cin >> input1;
cout << "\nPlease enter a second number: ";
cin >> input2;
cout << "\nUsing numbers: " << input1 << " and " << input2 << ", the larger one is: ";
if (input1 > input2)
cout << input1 << endl;
else if (input1 < input2)
cout << input2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\n\tThank you for running me :3\n" << endl;
return 0;
}
You basically have to refactor the code to replace the duplicate code part in your main function.
If you look closely you will see that code like this repeats:
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
So put that into a function:
void CompareNumbers(int nNum1, int nNum2)
{
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
}
And call this in your main function instead of duplicating the said code block.
Related
I am currently working on a (very very basic) program that is a tutorial for programming( ironic given my knowledge, I know). I was instructed to modularize my code so that each unit is in its own module. I'm guessing that means adding headers? I'm working with Visual Studios, if that helps at all. I've included my code below to help my bad explanation make sense. Thanks for any help you can provide!
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int Total;
int ans;
class Question
{
private:
string Question_Text;
string Answer_one;
string Answer_two;
string Answer_three;
int Correct_Answer;
int Question_Score;
public:
void setValues(string, string, string, string, int, int);
void askQuestion();
};
int main()
{
string username = "";
char choice=' ';
char c;
int x = 4;
int y = 5;
int z = x + y;
//welcome message
cout << "Hello user, please enter your name:";
cin >> username;
cout << "Welcome to the programming tutorial " << username << "." << endl;
//menu selection
while(choice != '5')
{
cout << "What would you like to do? (Unit 1 - Declaring Variables (1), Unit 2 - Input/ Output (2), Unit 3 - Conditionals (3), Quizzes (4) or Exit (5))";
cin >> choice;
if (choice == '1')
{
cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
cout << "The following are a few of the common datatypes used in programming.\n";
cout << "Character ==> char\n";
cout << "Integer ==> int, long, double\n";
cout << "Boolean ==> bool\n";
cout << endl;
cout << "When declaring a variable, you must put its datatype before the variable name.\n";
cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
cout << "We would write this as: \n";
cout << "int x = 4\n";
cout << "The program will now use the value 4 for the variable name 'x'\n";
cout << endl;
cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
cout << "If we wanted to add x and y and assign the sum to the variable 'z', we would write:\n";
cout << "int z = x + y\n";
cout << "Now when we use the variable 'z' in our program, it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
cout << "To test our code, we would write: " << endl;
cout << "cout<<'x + y'<< z << endl; \n";
cout << "If written correctly, it will display as: \n";
cout << "x + y = " << z << "." << endl;
}
if (choice == '2')
{
cout << "Now that we understand the basics of declaring variables, let's discuss displaying, or output of, information to a user.\n";
cout << "If you wanted to display a welcome message, for example, you would type:\n";
cout << "cout << 'Welcome';\n";
cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
cout << "Using this, you can ask the user for input.\n";
cout << "Enter c to continue...";
cin >> c;
cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
cout << "Assuming we previously declared this amount variable as 'int timesFlipped', we would 'cout' our question and the next line would read:\n";
cout << "cin>> timesFlipped; \n";
cout << "This will store the users input for the variable 'timesFlipped'\n";
cout << "You almost always end a line of code with a semi colon." << endl;
}
if (choice == '3')
{
cout << "This unit will cover conditional expressions." << endl;
}
if (choice == '4')
{
string Question_Text;
string Answer_one;
string Answer_two;
string Answer_three;
int Correct_Answer;
int Question_Score;
Question q1;
Question q2;
Question q3;
cout << username << ", you have chosen to take a quiz." << endl << endl;
int ans, score = 0;
cout << "Unit One Quiz - Variables " << endl << endl;
q1.setValues("How would you declare the value of 'x' as 12? ",
"x=12()",
"x==12()",
"x=12;()",
3,
1);
q2.setValues("What do you need to put before a variable when declaring it?",
"a name()",
"a value()",
"a datatype()",
3,
1);
q3.setValues("Which data type would you use for a number that includes a decimal value?",
"int()",
"double()",
"float()",
2,
1);
q1.askQuestion();
q2.askQuestion();
q3.askQuestion();
cout << "Your score out of a possible 3 is " << Total << endl;
}
if (choice == 'E')
{
cout << "Have a good day!";
break;
}
}
system("pause");
}
void Question::setValues(string q, string a1, string a2, string a3, int ca, int pa)
{
Question_Text = q;
Answer_one = a1;
Answer_two = a2;
Answer_three = a3;
Correct_Answer = ca;
Question_Score = pa;
}
void Question::askQuestion()
{
cout << endl;
cout << Question_Text << endl;
cout << "1. " << Answer_one << endl;
cout << "2. " << Answer_two << endl;
cout << "3. " << Answer_three << endl << endl;
cout << "Please enter your answer: " << endl;
cin >> ans;
if (ans == Correct_Answer)
{
cout << "That is correct!" << endl;
Total = Total + Question_Score;
}
else
{
cout << "Sorry, that is incorrect" << endl;
cout << "The correct answer was " << Correct_Answer << endl;
}
}
I'm guessing that means adding headers?
That's pretty much the idea.
In your case, you may want to:
Create a header name Question.h that includes the declaration of class Question.
Create a source file name Question.cpp and move the class definition there, ie all functions like void Question::askQuestion() etc.
Create a test file name test.cpp to put your main function, and remember to include the Question.h
As you are using Visual Studio, you can create a Project in advance then add all those files before compiling/building.
its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.
Here is what I have done so far, I did my best to label each bit of the code. It should also be noted that this was written in XCode, so it's running on a Mac.
/*
Ayush Sharma
4 November 2016
*/
#include <iostream>
#include <ctime>
using namespace std;
int main (){
//clearing the screen
system("clear");
//seeding the random
srand((unsigned int)time(NULL));
//variables & arrays
char answer;
int r, m, correct = 0;
string capitals[50] =
{"Montgomery", "Juneau", "Phoenix", "Little Rock", "Sacramento", "Denver", "Hartford", "Dover", "Tallahassee", "Atlanta", "Honolulu", "Boise", "Springfield", "Indianapolis", "Des Moines", "Topeka", "Frankfort", "Baton Rouge", "Augusta", "Annapolis", "Boston", "Lansing", "St. Paul", "Jackson", "Jefferson City", "Helena", "Lincoln", "Carson City", "Concord", "Trenton", "Santa Fe", "Albany", "Raleigh", "Bismarck", "Columbus", "Oklahoma City", "Salem", "Harrisburg", "Providence", "Columbia", "Pierre", "Nashville", "Austin", "Salt Lake City", "Montpelier", "Richmond", "Olympia", "Charleston", "Madison", "Cheyenne"};
string states[50] = {"Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"};
//title
cout << "***************************************************************\n";
cout << "* *\n";
cout << "* United States Capitals Quiz *\n";
cout << "* *\n";
cout << "***************************************************************\n\n";
for (int i = 0; i < 15; i++){
//Picking A Random State
r = rand() % 50;
//Checking if State is a Repeat
if (states[r] != "-1") {
cout << "What is the capital of " << states[r] << "? ";
//Picking Correct Answer Choice and Respective Layout
m = rand() % 4;
if (m == 0) {
cout << "\nA: " << capitals[r] << endl;
cout << "B: " << capitals[rand()%50] << endl;
cout << "C: " << capitals[rand()%50] << endl;
cout << "D: " << capitals[rand()%50] << endl;
}
if (m == 1) {
cout << "\nA: " << capitals[rand()%50] << endl;
cout << "B: " << capitals[r] << endl;
cout << "C: " << capitals[rand()%50] << endl;
cout << "D: " << capitals[rand()%50] << endl;
}
if (m == 2) {
cout << "\nA: " << capitals[rand()%50] << endl;
cout << "B: " << capitals[rand()%50] << endl;
cout << "C: " << capitals[r] << endl;
cout << "D: " << capitals[rand()%50] << endl;
}
if (m == 3) {
cout << "\nA: " << capitals[rand()%50] << endl;
cout << "B: " << capitals[rand()%50] << endl;
cout << "C: " << capitals[rand()%50] << endl;
cout << "D: " << capitals[r] << endl;
}
//Recieving Answer
cout << "Answer: ";
cin >> answer;
//Converting Letter to Number
if (answer == 'A' || answer == 'a') answer = 0; if (answer == 'B' || answer == 'b') answer = 1;
if (answer == 'C' || answer == 'c') answer = 2; if (answer == 'D' || answer == 'd') answer = 3;
//Comparing Answer to Correct Answer
if (m == answer) {
cout << "Correct!" << endl << endl;
correct++;
}else{
cout << "Incorrect! The correct answer was " << capitals[r] << "! \n\n";
}
//Removing State from Array
states[r] = "-1";
}else{
//If State was a Repeat, generate another State
i--;
}
}
//Printing Results
cout << "Number Correct: " << correct << "/15 or " << ((correct/15.00)*100) << "%!\n";
return 0;
}
The code works, almost. The problem is that answers are sometimes being repeated, such as in the scenario:
What is the capital of Wisconsin?
A. Madison
B. Frankfort
C. Jackson
D. Madison
Only A or D is the "correct" answer despite both having the same text (altough I'd rather make it impossible for the answers to repeat). I also would like to know if there is a more efficient way to create the layout of multiple choice questions. Thanks in advance!
-Ayush
Given that there are 50 values you want to draw from at random, without repetition, simply create an array or vector containing those values, shuffle it, and then access the elements of the shuffled array in order.
In C++11, this is easy using algorithms std::iota() and std::random_shuffle() from <algorithm>.
int value[50];
std::iota(std::begin(value), std::end(value), 0); // populate array with values 0 to 49
std::random_shuffle(std::begin(value), std::end(value));
Then in your outer loop, instead of r = rand()%50 use r=value[i].
std::begin() and std::end() are in standard header <iterator>.
The same idea can be used before C++11, but the method is a little different (C++11 didn't support std::begin(), std::end() or std::iota(), but equivalents are easy enough to implement).
Instead of value being an array, I'd create it as an std::vector<int>, also with 50 elements. I've illustrated above using an array, since you seem to be defaulting to using an array.
That's a pretty obvious thing to happen. An easy solution would be to make an array to hold the options already displayed. Use a while loop to add unique options to the array.You could check whether there is any repetition in the array using another function. Then, display capitals[r] along with three other options from the array.
bool noRepeat(int arr[], int o){
for(int i=0; i<3; i++){
if(arr[i] == o)
return false;
}
return true;
}
int main(){
...
//picking correct answer and determining layout
int m = rand()%4, n=0, y, options[3];
if (m == 0) {
while(n<3){
y = rand()%50;
if(noRepeat(options, y) && capitals[y]!=capitals[r])
options[n++] = y;
}
//display according to layout
cout << "\nA: " << capitals[r] << endl;
cout << "B: " << capitals[options[0]] << endl;
cout << "C: " << capitals[options[1]] << endl;
cout << "D: " << capitals[options[2]] << endl;
}
//do the same for the rest
...
}
Just like #Isaiah said you can use a while loop to test for the index generated to not be same your correct answer.
Something like :
int index = rand() % 50;
while(index == r)
{
index = rand() % 50;
}
cout << "B: " << capitals[index] << endl;
NOTE: this still can produce repeats of "incorrect answers", but i guess you get the point to avoid the repeats produced by rand. And obviously this is code is just to correct the repeats of corrects answer, you should be using rand at all as mentioned in comments by others.
Your problem is to pick three random capitals without repeats. So here's some pseudo code.
Put all capitals, except the true answer into a vector
Generate a random index into this vector
Use the capital at that index, and erase the capital from the vector
Repeat Steps 2 and 3 for the second and third random capitals. Note the random index should allow for the reduced vector size on each iteration.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm making a USD to MXN converter and I want to have it work both ways. The if statement works (tryed cout << "test"; and it worked) but it wont work when I replace it with the goto statement.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
if (user == 1)
{
goto USTMXN;
}
else
{
goto MXNTUS;
}
USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
goto END;
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
END:
system("PAUSE");
return EXIT_SUCCESS;
}
One of the most fundamental things we have to do as programmers is to learn to break problems into smaller problems. You are actually running into a whole series of problems.
I'm going to show you how to solve your problem. You may want to book mark this answer, because I'm pre-empting some problems you're going to run into a few steps down the line and preparing you - if you pay attention - to solve them on your own ;)
Let's start by stripping down your code.
Live demo here: http://ideone.com/aUCtmM
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int i;
std::cin >> i;
std::cout << "Enter a second number: ";
int j;
std::cin >> j;
std::cout << "i = '" << i << "', j = '" << j << "'\n";
}
What are we checking here? We're checking that we can ask the user two questions. That works fine.
Next is your use of goto, which I strongly recommend you do not use. It would be better to use a function. I'll demonstrate with your goto case here first:
#include <iostream>
int main()
{
int choice;
std::cout << "Enter choice 1 or 2: ";
std::cin >> choice;
if ( choice == 1 )
goto CHOSE1;
else if ( choice == 2 )
goto CHOSE2;
else {
std::cout << "It was a simple enough question!\n";
goto END;
}
CHOSE1:
std::cout << "Chose 1\n";
goto END;
CHOSE2:
std::cout << "Chose 2\n";
goto END;
END:
std::cout << "Here we are at end\n";
}
live demo: http://ideone.com/1ElcV8
So goto isn't the problem.
That leaves your use of variables. You've really mixed things up nastily by having a second set of variables (mm, uu). Not only do you not need to have these, you're doing something very naughty in that these variables only exist inside one scope and not the other. You can "get away" with this but it will come back to haunt you later on.
The difference in your two main streams of code is the variable names. The second conversion case looks like this:
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
The problem here is that you have - accidentally - used the variable "m" in your output. It's what we call uninitialized.
cout << "US Dollars: " << m << endl;
That m in the middle should be mm.
Your compiler should actually be warning you about this. If it's not, and you're just setting out learning, you should figure out how to increase the compiler warning level.
It would be better to make a function to do the conversions; you could make one function for each direction, but I've made a function that handles both cases:
#include <iostream>
static const double US_TO_MXN = 12.99;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
std::cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
std::cin >> original;
std::cout << to << ": " << (original * exchange) << '\n';
}
int main() // this is valid since C++2003
{
std::cout << "US/MXN Converter\n"
"1 US = " << US_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
int choice = 0;
// Here's a better demonstration of goto
GET_CHOICE:
std::cout << "Which conversion do you want to perform?\n"
"[1] US to MXN\n"
"[2] MXN to US\n"
"Selection: ";
std::cin >> choice;
if (choice == 1)
convert("US Dollars", "Pesos", US_TO_MXN);
else if (choice == 2)
convert("Pesos", "US Dollars", 1 / US_TO_MXN);
else {
std::cerr << "Invalid choice. Please try again.\n";
goto GET_CHOICE;
}
// this also serves to demonstrate that goto is bad because
// it's not obvious from the above that you have a loop.
}
ideone live demo: http://ideone.com/qwpRtQ
With this, we could go on to clean things up a whole bunch and extend it:
#include <iostream>
using std::cin;
using std::cout;
static const double USD_TO_MXN = 12.99;
static const double GBP_TO_MXN = 22.03;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
cin >> original;
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
}
int main() // this is valid since C++2003
{
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
for ( ; ; ) { // continuous loop
cout << "Which conversion do you want to perform?\n"
"[1] USD to MXN\n"
"[2] MXN to USD\n"
"[3] GBP to MXN\n"
"[4] MXN to GBP\n"
"[0] Quit\n"
"Selection: ";
int choice = -1;
cin >> choice;
cout << '\n';
switch (choice) {
case 0:
return 0; // return from main
case 1:
convert("US Dollars", "Pesos", USD_TO_MXN);
break;
case 2:
convert("Pesos", "US Dollars", 1 / USD_TO_MXN);
break;
case 3:
convert("British Pounds", "Pesos", GBP_TO_MXN);
break;
case 4:
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN);
break;
default:
cout << "Invalid selection. Try again.\n";
}
}
}
http://ideone.com/iCXrpU
There is a lot more room for improvement with this, but I hope it helps you on your way.
---- EDIT ----
A late tip: It appears you're using visual studio, based on the system("PAUSE"). Instead of having to add to your code, just use Debug -> Start Without Debugging or press Ctrl-F5. It'll do the pause for you automatically :)
---- EDIT 2 ----
Some "how did you do that" points.
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
I very carefully didn't do the using namespace std;, when you start using more C++ that directive will become the bane of your existence. It's best not to get used to it, and only let yourself start using it later on when you're a lot more comfortable with C++ programming and more importantly debugging odd compile errors.
But by adding using std::cout and using std::cin I saved myself a lot of typing without creating a minefield of function/variable names that I have to avoid.,
What does the line do then:
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
The '\n' is a single character, a carriage return. It's more efficient to do this than std::endl because std::endl has to go poke the output system and force a write; it's not just the end-of-line character, it actually terminates the line, if you will.
int(original * exchange)
This is a C++ feature that confuses C programmers. I'm actually creating a "temporary" integer with the result of original * exchange as parameters.
int i = 0;
int i(0);
both are equivalent, and some programmers suggest it is better to get into the habit of using the second mechanism so that you understand what happens when you later run into something called the "most vexing parse" :)
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN)
The 1 / x "invert"s the value.
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
This is likely to be confusing. I'm mixing metaphors with this and I'm a little ashamed of it, but it reads nicely. Again, employ the concept of breaking problems up into smaller problems.
cout << "Hello " "world" << '\n';
(note: "\n" and '\n' are different: "\n" is actually a string whereas '\n' is literally just the carriage return character)
This would print
Hello world
When C++ sees two string literals separated by whitespace (or comments) like this, it concatenates them, so it actually passes "Hello world" to cout.
So you could rewrite this chunk of code as
cout << "Foreign Currency Converter\n1 USD = ";
cout << USD_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n1 GBP = ";
cout << GBP_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n\n";
The << is what we call "semantic sugar". When you write
cout << i;
the compiler is translating this into
cout.operator<<(i);
This odd-looking function call returns cout. So when you write
cout << i << j;
it's actually translating it to
(cout.operator<<(i)).operator<<(j);
the expression in parenthesis (cout.operator<<(i)) returns cout, so it becomes
cout.operator<<(i); // get cout back to use on next line
cout.operator<<(j);
Main's fingerprint
int main()
int main(int argc, const char* argv[])
Both are legal. The first is perfectly acceptable C or C++. The second is only useful when you plan to capture "command line arguments".
Lastly, in main
return 0;
Remember that main is specified as returning int. The C and C++ standards make a special case for main that say its the only function where it's not an error not to return anything, in which case the program's "exit code" could be anything.
Usually its best to return something. In C and C++ "0" is considered "false" while anything else (anything that is not-zero) is "true". So C and C++ programs have a convention of returning an error code of 0 (false, no error) to indicate the program was successful or exited without problems, or anything else to indicate (e.g. 1, 2 ... 255) as an error.
Using a "return" from main will end the program.
Try to change youre code for sth like this. Using goto label is not recommended.
Main idea of switch statement :
int option;
cin >> option
switch(option)
{
case 1: // executed if option == 1
{
... code to be executed ...
break;
}
case 99: //executed id option == 99
{
... code to be executed
break;
}
default: // if non of above value was passed to option
{
// ...code...
break;
}
}
Its only example.
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
switch(user )
{
case 1 :
{
//USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
break;
}
}
default :
{
//MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
break;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
I am writing a simple program that finds the factors of a list of integers through Linux Redirection. I am almost done, but I am stuck on one part. Here is my program so far:
#include<iostream>
using namespace std;
int main()
{
int counter = 0;
int factor;
cin >> factor;
while (cin)
{
if (factor < 0)
break;
cout << "The factors of " << factor << " are " << endl;
for(int i=factor; i>=1; i--)
if (factor % i == 0)
{
counter++;
cout << i << endl;
}
cout << "There are " << " factors." << endl;
cout << endl;
cin >> factor;
}
return 0;
}
Now the problem I have is in the line " cout << "There are " << " factors." << endl; ". I'm not sure how to calculate the number of factors output by the program.
For example:
The factors of 7 are
1
7
There are 2 factors.
How would I go about calculating and outputting the "2" in this example.
Help is greatly appreciated.
Instead of
cout << "There are " << " factors." << endl;
use
cout << "There are " << counter << " factors." << endl;
If you do that, you have to move the line where you define counter.
Instead of it being the first line in main, it needs to be moved to be the first line in the while loop.