C++ Variables not updating in loop - c++

For some reason the values in the loop do not update. Instead of taking the new values they are assigned in the loop they stay the same as when first assigned. Why is this?
using namespace std;
int main() {
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
cout << "Enter the polulation of town A and of town B:" << endl;
cin >> town_A_Pop >> town_B_Pop;
cout << "Enter the growth rate of town A and of town B:" << endl;
cin >> town_A_Growth >> town_B_Growth;
do {
town_A_Pop = town_A_Pop * (1 + (town_A_Growth / 100));
cout << town_A_Pop << endl;
town_B_Pop = town_B_Pop * (1 + (town_B_Growth / 100));
cout << town_B_Pop << endl;
years++;
}
while (town_A_Pop < town_B_pop);
cout << "It took " << years << " years for Town A to overtake Town B." << endl;
cout << "Town A Population: " << town_A_Pop << endl;
cout << "Town B Population: " << town_B_Pop << endl;
return 0;
}

I assume that town_A_Pop and town_B_Pop don't update.
If town_A_Growth is less than 100(and greater or same than 0) then (town_A_Growth / 100) will evaluate to 0 and (1 + (town_A_Growth / 100)) will evaluate to 1.
In that case, town_A_Pop = town_A_Pop * 1 so it will stay same.
Same goes to town_B_Pop.
To fix the problem, you can change variables into float or double, or multiply first then divide by 100 like below:
do {
town_A_Pop = (town_A_Pop * (100 + town_A_Growth)) / 100;
cout << town_A_Pop << endl;
town_B_Pop = (town_B_Pop * (100 + town_B_Growth)) / 100;
cout << town_B_Pop << endl;
years++;
}
while (town_A_Pop < town_B_pop);
It will still won't get bigger if both population and growth are too small, though.

Your problem is Type Variables Error
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
change to
double town_A_Pop;
double town_A_Growth;
double town_B_Pop;
double town_B_Growth;
double years;
This should be ok. Because if using int to do division it not able return decimal number.
Like:
int tmp = 1;
int division = tmp / 5; //This result will return 0 , not return 0.2

Related

Structuring and generating a deck of cards with a loop in c++ [duplicate]

This question already has an answer here:
C++ - using enums to generate a deck of cards
(1 answer)
Closed 2 years ago.
it's in c++
The idea was to set it up so that it will keep looping through all the cards to keep getting different results and answers until all 52 cards are gone i dont know the exact placmet for it I know its
for(int i = 0; i < 5; i++)
{
cout << i << endl;
}
I wasn't quite sure how to set up the array If I just did it like string {ace, one two} and so on.. but I have the array labeled 52 even typing them all out its only 13 number repeated 4 times in 4 suits so would you class them all separately? Or is there something for that?
#include <iostream>
using namespace std;
class cardGame;
int main()
{
int bet;
int dealer[52] = { 13, 13, 13, 13 };
int player[52] = { 13, 13, 13, 13 };
int dealerCard1;
int dealerCard2;
int playerCard1;
int playerCard2;
int dealerTotal;
int playerTotal;
int shuffle;
cout << "This is My attempt at BlackJack" << endl;
cout << endl;
cin >> bet;
cout << "Player enter amount to bet: $ ";
cout << endl;
cin >> shuffle;
cardGame::playeer(playerCard1 + playerCard2 = playerTotal);
cardsGame.playerCard1 = 0;
cardsGame.playerCard2 = 0;
cardsGame.playerTotal = 0;
cout << "the First card is: " << cardsGame.playerCard1 = 0 << endl;
cout << "The second card is: " << cardsGame.playerCard = 0 << endl;
cout << "Your total is: " << cardsGame.playerTotal = 0 << endl;
cardGame::playeer(playerCard1 + playerCard2 = playerTotal);
if (playerCard1 + playerCard2 == 21)
{
cout << "WINNER WINNER CHICKEN DINNER!" << endl;
};
else (playerCard1 + playerCard2 > 21)
{
cout << "What a dissapointment you are to everyone!" << endl;
};
if (playerCard1 + playerCard2 > dealerTotal)
{
cout << "WINNER WINNER CHICKEN DINNER!" << endl;
};
else (playerCard1 + playerCard2 == dealerTotal)
{
cout << "What a dissapointment you are to everyone!"
}
cardGame::dealer(dealerCard1 + dealerCard2 = dealerTotal);
cardsGame.dealerCard1 = 0;
cardsGame.dealerCard2 = 0;
cardsGame.dealerTotal = 0;
cout << "the First card is: " << cardsGame.dealerCard1 = 0 << endl;
cout << "The second card is: " << cardsGame.dealerCard2 = 0 << endl;
cout << "Your total is: " << cardsGame.dealerTotal = 0 << endl;
cardGame::dealer(dealerCard1 + playerCard2 = playerTotal);
if (dealerCard1 + dealerCard2 == 21)
{
cout << "What a dissapointment you are to everyone!" << endl;
};
else (dealerCard1 + dealerCard2 > 21)
{
cout << "WINNER WINNER CHICKEN DINNER" << endl;
}
if (dealerCard1 + dealerCard2 > playerTotal)
{
cout << "What a dissapointment you are to everyone!" << cout endl:
};
else (dealerCard1 + dealerCard2 < playerTotal)
{
cout << "What a dissapointment you are to everyone!"
}
}
I don't know c++ (or blackjack); but below is an example in Javascript which illustrates some concepts and might push you in the right direction.
In terms of structure you might want something like:
// Set up your 'deck'
deck = {
hearts: [],
spades: [],
diamonds: [],
clubs: []
}
// The object 'deck' has four properties (hearts, spades...), each of which is an empty array.
// Use a loop to add your 'cards'
Object.keys(deck).forEach(suit => {
for (i = 1; i < 14; i++) {
deck[suit].push(i);
}
});
// For each property in the object 'deck', push ascending consecutive integers starting from the number 1 to each array, until the number 14 is reached.
This gives you:
deck = {
hearts: [1,2,3,4,5,6,7,8,9,10,11,12,13],
spades: [1,2,3,4,5,6,7,8,9,10,11,12,13],
diamonds: [1,2,3,4,5,6,7,8,9,10,11,12,13],
clubs: [1,2,3,4,5,6,7,8,9,10,11,12,13]
}

How to make the output in tabular form

Who could help me, can't figure out how to make my output for Charge-column. I need to make that output right under that charge column, but every time when I hit ENTER it makes a new line hence my output appears in new line. Also there is a zero after each output, don't know where is that come from. Here is my code:
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
float calculateCharges(double x);
int main()
{
int ranQty; //calculates randomly the quantity of the cars
double pTime; // parking time
srand(time(NULL));
ranQty = 1 + rand() % 5;
cout << "Car\tHours\tCharge" << endl;
for(int i = 1; i <= ranQty; i++)
{
cout << i << "\t";
cin >> pTime ;
cout << "\t" << calculateCharges(pTime) << endl;
}
return 0;
}
float calculateCharges(double x)
{
if(x <= 3.0) //less or equals 3h. charge for 2$
{
cout << 2 << "$";
}
else if(x > 3.0) // bill 50c. for each overtime hour
{
cout << 2 + ((x - 3) * .5) << "$";
}
}
You are hitting ENTER key each time to send your pTime from the command line to your program's standard input. This causes a new line. The new line is what causes the console to hand your input over to the program in the first place.
In order to print properly, you can simply store the pTime to an array(i.e, preferably in std::vector, as #user4581301 mentioned); calculate the required and print it.
something like:
#include <vector>
ranQty = 1 + rand() % 5;
std::cout << "Enter " << ranQty << " parking time(s)\n";
std::vector<double> vec(ranQty);
for(double& element: vec) std::cin >> element;
std::cout << "Car\tHours\tCharge" << std::endl;
for(int index = 0; index < ranQty; ++index)
std::cout << index + 1 << "\t" << vec[index] << "\t" << calculateCharges(vec[index]) << "$" << std::endl;
there is a zero after each output, don't know where is that come from.
float calculateCharges(double x); this function should return a float and your definition is something like a void function. Solution is:
float calculateCharges(double x)
{
if(x <= 3.0) return 2.0f; // --------------> return float
return 2.0f + ((x - 3.0f) * .5f) ; // --------------> return float
}

Temperature table using for loop c++ [closed]

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 7 years ago.
Improve this question
Super new to coding and I've been stuck for awhile on this question. I need to make a program that inputs the temperature in Celsius and an increment that is inputted for a total of 20 lines. In the process it converts to Fahrenheit, Kelvin, and Rankine. That is all fine but I can't get the values to increment by my input.
e.g., As it should look:
Enter temperature in Cel: 50
Enter increment: 5
Cel Far Kel Rank
1 - 50 ...............................
2 - 55 ..............................
3 - 60 ..............................
.
.
.
.
20 - 150 .............................
I can't get the values to increment at all. Being reading my notes and looking online to understand the issue but no luck.
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main()
{
int CELS; // celsius entry
int x; // x = input value for increment
double FAH = (CELS * (9.0 / 5) + 32); // farenheit conversion
double KEL = (CELS + 273.15); // kelvin conversion
double RANK = ((CELS + 273.15) * (9.0 / 5)); // rankine conversion
cout << "Enter the temperature in celsius: ";
cin >> CELS;
while ((CELS < -273.15) || (CELS > 5000))
{
cout << "ERROR: out of range." << endl;
cout << "Enter the temperature in celsius: ";
cin >> CELS;
}
cout << "Enter the increment value: ";
cin >> x;
cout << endl;
cout << " # Cels Fahr Kel Rank" << endl;
cout << right;
for (int i = 1; i <= 20; i++)
{ //
for (double j = CELS; j <= CELS; x++)
{ //
for (double k = (CELS * (9.0 / 5) + 32);
k <= (CELS * (9.0 / 5) + 32); x++)
{
for (double m = (CELS + 273.15); m <= (CELS + 273.15); x++)
{
for (double n = ((CELS + 273.15) * (9.0 / 5));
n <= ((CELS + 273.15) * (9.0 / 5)); x++)
{
cout << setw(10) << i << setw(10) << j << setw(10) << k
<< setw(10) << m << setw(10) << n << endl;
}
}
}
}
}
}
And ignore why I have my formulas in the for loop. Formulas were not working using the declared variables so have just done this in the mean time.
You can use some user defined functions to calculate the conversion from Celsius to the other units.
Then you only need one loop:
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::setw;
// define some constant
const double zero_point = 273.15;
constexpr double factor = 9.0 / 5.0;
const double max_cels = 5000;
// farenheit conversion
double cels_to_far( double cels ) {
return cels * factor + 32.0;
}
// kelvin conversion
double cels_to_kel( double cels ) {
return cels + zero_point;
}
// rankine conversion
double cels_to_ran( double cels ) {
return ( cels + zero_point ) * factor;
}
int main()
{
double temp_cels;
double delta_t;
cout << "Enter the temperature in celsius: ";
cin >> temp_cels;
while ((temp_cels < -zero_point) || (temp_cels > 5000)) {
cout << "ERROR: out of range.\n";
cout << "Enter the temperature in celsius: ";
cin >> temp_cels;
}
cout << "Enter the increment value: ";
cin >> delta_t;
cout << "\n # Cels Fahr Kel Rank\n";
// output loop
for ( int i = 0; i < 20; ) {
cout << setw(10) << ++i << std::fixed << std::setprecision(2)
<< setw(10) << temp_cels
<< setw(10) << cels_to_far(temp_cels)
<< setw(10) << cels_to_kel(temp_cels)
<< setw(10) << cels_to_ran(temp_cels) << std::endl;
temp_cels += delta_t;
}
}
The output is as expected ( 50° Celsius and increment of 5°):
# Cels Fahr Kel Rank
1 50.00 122.00 323.15 581.67
2 55.00 131.00 328.15 590.67
3 60.00 140.00 333.15 599.67
4 65.00 149.00 338.15 608.67
5 70.00 158.00 343.15 617.67
6 75.00 167.00 348.15 626.67
7 80.00 176.00 353.15 635.67
8 85.00 185.00 358.15 644.67
9 90.00 194.00 363.15 653.67
10 95.00 203.00 368.15 662.67
11 100.00 212.00 373.15 671.67
12 105.00 221.00 378.15 680.67
13 110.00 230.00 383.15 689.67
14 115.00 239.00 388.15 698.67
15 120.00 248.00 393.15 707.67
16 125.00 257.00 398.15 716.67
17 130.00 266.00 403.15 725.67
18 135.00 275.00 408.15 734.67
19 140.00 284.00 413.15 743.67
20 145.00 293.00 418.15 752.67
You need exactly one for loop, incrementing by x. ( The nested for loops are a mistake )
Start with the one, single for loop that you need: the one that counts through the lines of the output table.
In the body of the loop, calculate everything you need for that line, and output it.
Something like this:
for( int line_count = 0;
line_count < 20;
line_count++ )
{
double line_temp_celsius =
start_celsius + line_count * celsius_increment;
// calculate the other values based line_temp_celsius
...
}
The calculation must be in the loop where you change the value of CELS.
There should be a single loop. The result looks like this. See live demo
for (int i = 1; i <= 20; i++, CELS+=x)
{
double FAR = (CELS * (9.0 / 5) + 32); // farenheit conversion
double KEL = (CELS + 273.15); // kelvin conversion
double RANK = ((CELS + 273.15) * (9.0 / 5)); // rankine conversion
cout << setw(10) << i << setw(10) << CELS << setw(10) << FAR
<< setw(10) << KEL << setw(10) << RANK << endl;
}

Explanation of C++ Code

I'm currently working on a program that outputs the number 1089 (i.e the Magic Number) of a three digit integer who's first digit is greater than its last. I have some code typed up, but am not receiving 1089, instead I'm receiving 891. Could anyone offer some explanation as to why.
//Uses a cout to inform user will be using the number 412 as an example.
//Uses a cout to explain to user the number needs to be reversed.
cout << "Alright, let's walk through an example, using the number 412." << endl;
int numExample = 412;
cout << "Please input 412" << endl;
cin >> numExample;
cout << "First, the number 412 is reversed." << endl;
//The following is done for reversing the number 412:
int reverseNum = 0, remainder = 0;
while (numExample)
{
remainder = numExample % 10;
reverseNum = (reverseNum * 10) + remainder;
numExample = numExample / 10;
}
cout << "The reverse of 412 is " << reverseNum << endl;
cout << "Next, we want to subtract the reverse of the original number from its reverse" << endl;
cout << "This gives us 198" << endl;
cout << "From there, we want to reverse 198." << endl;
//The same procedure is used to reverse 198
int numExample2 = 198;
cout << "Please enter 198" << endl;
cin >> numExample2;
int reverseNum2 = 0, remainder2 = 0;
while (numExample2)
{
remainder2 = numExample2 % 10;
reverseNum2 = (reverseNum2 * 10) + remainder2;
numExample2 = numExample2 / 10;
}
cout << "The reverse of 198 is " << reverseNum2 << endl;
int magicNumber = (reverseNum2 + numExample2);
cout << "Following that, we want to add 891 to 189 which gives us " << magicNumber << endl;
Try writing a function to handle this so your code is cleaner (It will also make it easier for people to help you!)
#include <iostream>
#include <cmath>
using namespace std;
int reverseDigit(int num); // For example purposes
int _tmain(int argc, _TCHAR* argv[])
{
int Number1,
Number2,
temp1,
temp2,
Result;
cout << "Enter the number 412: ";
cin >> Number1;
temp1 = reverseDigit(Number1);
temp1 = Number1 - temp1;
cout << "Enter the number 198: ";
cin >> Number2;
temp2 = reverseDigit(Number2);
Result = temp1 + temp2;
cout << "The magic number is: " << Result << endl;
return 0;
}
int reverseDigit(int num)
{
int reverseNum = 0;
bool isNegative = false;
if (num < 0)
{
num = -num;
isNegative = true;
}
while (num > 0)
{
reverseNum = reverseNum * 10 + num % 10;
num = num / 10;
}
if (isNegative)
{
reverseNum = -reverseNum;
}
return reverseNum;
}
I realize you're not working with negatives so you can remove that bit if you chose to use this, you can also expand on it... That being said this will make the actual " Reversing process " easier to work with and improve upon and read.

Division answer not executing properly

I am having trouble with the following line of code:
double answer;
answer = num[count] / den[count]
cout << " Fraction" << count + 1 << " " << num[count]
<< " / " << den[count] << " = " << answer << endl;
How come my rendition of answer is not working? Am I overlooking something? I am using arrays and am getting the data from a separate text file. When I use the code above I get the numbers that are to be divided correctly but the answer is incorrect. It comes out to be a random number usually 0 or 1.
Here is my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void read_data(int num[], int den[], int size);
void showValues(int num[],int den[], int size);
int main()
{
const int size1 = 12;
const int size2 = 12;
ifstream dataIn;
int num[12];
int den[12];
read_data(num,den,size1);
cout << "Here are the fractions: " << endl;
showValues(num,den,size1);
system("PAUSE");
return 0;
}
void read_data(int num[], int den[], int size)
{
ifstream dataIn;
dataIn.open("walrus.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
dataIn.close();
}
void showValues(int num[],int den[], int size)
{
int count;
for (count = 0; count < size; count++)
{
if (den[count] == 0)
{
cout << " Fraction" << count + 1 << " "
<< num[count] << " /" << den[count]
<< " Is invalid" << endl;
}
else
{
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
}
}
}
#main ifstream dataIn;
You are not using this object
#function read_data :
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
Assuming ur file looks like :
1 2 23 32 44 // numerators
2 3 1 99 24 // den
The proper way to read is :
int count = 0;
while( count < size && dataIn >> num[count++] ) // numerators
;
count = 0;
while( count < size && dataIn >> den[count++] )
;
#function showValues :
try changing
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
to :
double answer = static_cast<double>(num[count]) / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count] << " = " << answer << endl;
In C and C++, if you do,
double answer = 10 / 3;
your answer will be 3. The reason is you have 2 integers and an integer division will take place. The resulting output is then implicitly converted into a double. So the steps are,
double answer = 10 / 3
double answer = 3
double answer = 3.0
To fix this, you tell the compiler that you want this to be treated as floating point division.
double answer = 10.0 / 3;
This works by,
double answer = 10.0 / 3
double answer = 10.0 / 3.0
double answer = 3.33333333...
The compiler will implicitly cast the 3 into a larger double type, 3.0.
So in your code, you have to convert integer division into floating point division by casting at least one of the division arguments into a double.
double foo = num[count] / den[count];
simply becomes
double foo = num[count] / static_cast<double>(den[count]);
Alternatively, if one or both of the arrays were of double type, you would not have this problem requiring casts.