Having garbage numbers while calculating percentage - c++

So, I hate to ask, but, I'm having some issue with this, I'm new to C++ and I'm just starting out. Everything is done for the most part. Expect for a little thing.
Line 35-36 should be calculating the average (Which for some reason, I haven't been able to get it to work.)
Line 41-47 should print out the percentage that heads/tails was landed on with precision to one decimal, and then print out the correct numbers of * to represent the percentage.
But, when I run it, my heads/tail count is messed up. As well as my percentage numbers. I'm just looking for a push in the right direction.
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
using std::fixed; using std::setprecision;
int main()
{
srand(time(0));
int userInput,
toss,
headsCount,
tailsCount;
double headsPercent = 0,
tailsPercent = 0;
cout << "How many times do you want to toss the coin? ";
cin >> userInput;
while(userInput < 0)
{
cout << "Please enter a positive number: ";
cin >> userInput;
}
for(int i = 1; i < userInput; i++)
{
toss = rand() % 2;
if(toss == 0)
headsCount++;
else
tailsCount++;
}
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
cout << "Heads: " << headsCount << endl
<< "Tails: " << tailsCount << endl << endl;
cout << "Heads Percentage: " << fixed << setprecision(1) << headsPercent << " ";
for(int b = 0; b < headsPercent; b++)
cout << "*";
cout << "\nTails Percentage: " << tailsPercent << " ";
for(int b = 0; b < tailsPercent; b++)
cout << "*";
return 0;
}

In addition to the uninitialized variables here, that others have pointed out, the calculations are all wrong.
Take out paper and pencil, and run some your own calculations the old-fashioned way.
Let's say there were five tosses, three heads, two tails. This means that (after fixing the uninitialized variables):
userInput=5
headsCount=3
tailsCount=2
Now, here's how you're calculating your supposed percentages:
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
So, using your own numbers, you will get:
headsPercent = 5 / 3 * 100
tailsPercent = 5 / 2;
Does this look right to you? Of course not. You can do the arithmetic yourself. Divide 5 by 3 and multiply by 100. This is integer division, so five divided by three is 1, multiplied by 100 is 100. Five divided by two is two. So you get 100% and 2% here.
Of course, that's wrong. Two and three times, out of five, is 40% and 60%, respectively.
Writing a program means:
A) Figure out how calculations need to be made
B) Write the code to do the calculations.
You're still on step A. You need to figure out how you want to make these calculations so they're correct, first.
This has nothing really to do with C++. If you were using any other language, and coded this, in that manner, you'll get the same wrong answers.
The only thing this might have to do with C++ is that integer division, in C++ does not produce a fractional amount. It's integer division. But that's not your only problem.

Firstly u have to correct ur basics of mathematics.
Calculating %age means
example
(Marks obtained)/(Total marks)*100
Not (Total marks/marks obt)*100
Dividing any no by 0 is not defined. So if ur current code randomly assign toss or head =0, then obviously u will have errors.
Secondly talking about codes, U should either initialize i from 0 , or u should use
for (i=1; i<=userInput; i++)
As otherwise the head+toss value will be userInput-1.
Also remember to initialise variables like
Int headsCount=0;
etc. As the variable will take any random value if not initialised to a fixed no. (Though it does not creates a problem here)
And just change the datatype
int userInput,
toss,
headsCount,
tailsCount;
To
double userInput,
toss,
headsCount,
tailsCount;
This will solve your problem.
Advice: Please use
using namespace std;
in the starting of ur programs as u have to type a lot of std::

Welcome to C++. You need to initialise your variables. Your compiler should have warned you that you were using a variable without initialising it. When you don't initialise a value, your program has undefined behaviour.
I'm talking about headsCount and tailsCount. Something like this should be fine:
int headsCount = 0, tailsCount = 0;
Also note that your loop should start at 0, not 1, since you are using the < operator on the final condition.
Finally, your percentage calculations are backwards. It should be:
headsPercent = headsCount * 100 / userInput;
tailsPercent = tailsCount * 100 / userInput;
Now, there's a weird thing that might happen because you are using integer division. That is, your percentages might not add up to 100. What's happening here is integer truncation. Note that I dealt with some of this implicitly using the 100x scale first.
Or, since the percentages themselves are double, you can force the calculation to be double by casting one of the operands, thus avoiding integer truncation:
headsPercent = static_cast<double>(headsCount) / userInput * 100;
In fact, since the only two possibilities are heads and tails, you only need to count one of them. Then you can do:
tailsPercent = 100 - headsPercent;

1) This loop should start from 0:
for(int i = 1; i < userInput; i++)
2) The divisions are not correct:
//headsPercent = userInput / headsCount * 100;
//tailsPercent = userInput / tailsCount;
headsPercent = headsCount / userInput * 100;
tailsPercent = tailsCount / userInput * 100;
3) Finally:
cout << "\nTails Percentage: " << fixed << setprecision(1) << tailsPercent << " ";

Related

Not understanding why code isn't producing desired answer

The assignment I've been given is asking me to find out how many trees can be put in a certain length and how much total space they'd take up including the required space between the trees. Thanks to some help I've been able to get the tree total correct, but the total space taken up is incorrect. What can I do to fix this.
input is: length = 10, TRadius = .5, ReqSpace = 3
desired output is: TreeTot = 2
Total space should be 1.57
Actual output is: TreeTot = 2 Total Space is 6.1
Here is the code I'm using.
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 3.14;
int main()
{
double length;
double TRadius;
double ReqSpace;
int TreeTot = 0;
cout << "enter length of yard: ";
cin >> length;
cout << "enter radius of a fully grown tree: ";
cin >> TRadius;
cout << "required space between fully grown trees: ";
cin >> ReqSpace;
while (length > TRadius * 2 + ReqSpace) {
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
}
cout << "The total space taken up is ";
cout << setprecision(2) << TreeTot * TRadius * PI + ReqSpace << endl;
cout << "The total amount of trees is ";
cout << TreeTot;
return 0;
}
These two lines:
TreeTot + 1;
length - (TRadius * 2) + ReqSpace;
are valid statements, but they're just expressions. You calculate a value, but don't do anything with it. TreeTot + 1... and then what? You need to assign the calculated value to something. Presumably you're wanting to increase the TreeTot and decrease the length. Just assign the values like so:
TreeTot = TreeTot + 1;
length = length - (TRadius * 2) + ReqSpace;
Or use the shorthand for modifying and assigning the result to the same value:
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
Your answer will probably still be wrong because the if-statement only runs once - you never tell it you want it to do the code within multiple times. If you change the if to a while then the code will loop until length is too small to satisfy the condition.

C++ series summation code giving different answers on large input

I am adding numbers from 1 to n in C++. I have used both the iteration method and mathematical formula. The code works fine for up to 9 digits.
But when I give input a 10 digit number, the formula and iteration methods give separate answers.
I have tried to look it up on google but couldn't find any solution for this. My code:
#include <bits/stdc++.h>
using namespace std;
int main(){
unsigned long long i, n, sum = 0, out_put;
cout << "Sum of numbers from 1 to: ";
cin >> n;
/// using mathematical formula
out_put = n*(n+1);
out_put = out_put/2;
cout << " = " << out_put << endl;
/// using iteration
for (i=1; i<=n; i++){
sum = sum+i;
}
cout << " == " << sum << endl;
return 0;
}
How do know which one is the correct one? If I assume the formula can't be wrong then why is the iteration method giving incorrect answer? I have used unsigned long long to prevent overflow but still didn't work.
What you are seeing is overflow happening on your calculations at different points. 9,999,999,999 * 10,000,000,000 is ~9.9e19 while an unsigned long long holds ~1.8e19. So the result wraps around and you get one answer.
Your for loop is also going to overflow but it is going to do so at a different point meaning the answers will diverge from one another since the modulo arithmetic is happening with a smaller number.
Your problem is that n*(n+1) can be too large to store in an unsigned long long, even though the end result (half of that) which you calculate via iteration may still fit.
Assuming your unsigned long long has 64 bits, it can hold integers up to 18446744073709551615. Anything above that will restart from 0.
Edit: As Nathan points out, you can of course have both calculations overflow. The sum would still give the correct result modulo 2^64, but the direct calculation can be off because the division does not generally yield the same result modulo 2^64 after you have wrapped around.
#include <bits/stdc++.h>
using namespace std;
int main(){
unsigned long long i, n, sum = 0, out_put;
cout << "Sum of numbers from 1 to: ";
cin >> n;
/// using mathematical formula
out_put = n*(n+1);
out_put = out_put/2;
cout << " = " << out_put << endl;
/// using iteration
for (i=1; i<=n; i++){
sum = sum+i;
}
cout << " == " << sum << endl;
return 0;
}

How do I calculate an updating average speed for each year in a table using c++?

In your program, you will have the user enter what percentage improvement in
rocket speeds (up to but not exceeding light speed!) each year. Your program will
then ask the user the maximum number of years that they are willing to wait on
earth before they leave. Use while loops in this step to implement simple error
checking by asking the user repeatedly until they give a valid input. Percentage
must be somewhere between 0 and 100 and the years waiting must be a positive
integer.
Next, your program will generate a table using a for loop. That table will have
four columns with one row for leaving immediately followed by one row for each
year the user is willing to wait. The first column will contain the departure year.
The second column contains the rocket speed that rockets will be able to achieve
that year. The new rocket speed each year is calculated with this equation:
velocity = velocity + (lightspeed - velocity) * (improvement/100)
I was able to correctly print out each year in the table I am trying to make, but I am having trouble figuring out how to use a loop to find the speed of the rocket for each year using a loop. I am pretty sure I am supposed to use a nested for loop, but with the code I have right now, it is stuck in an infinite loop. Any guidance in the right direction would be appreciated!
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
int percentIncrease = 0;
int maxYears = -1;
float speedLight = 299792;
while((percentIncrease <= 0) || (percentIncrease >= 100))
{
cout << "What percentage do rocket speeds increase by each year?" << endl;
cin >> percentIncrease;
}
while(maxYears < 0)
{
cout << "What is the maximum number of years you are willing to wait on
earth before you leave?" << endl;
cin >> maxYears;
}
cout << "Start year|\tAvg Speed|\tEarth ETA|\tYour ETA" << endl;
for(int i = 2018; i <= (maxYears + 2018); ++i)
{
cout << i << endl;
for(int j = 10000; i <= (maxYears + 2018); j = j + (speedLight - j) *
(percentIncrease/100))
{
cout << "\t" << j << endl;
}
}
return 0;
}
I think a good way to think about it is that you will have to print the table row by row. So your first for loop seems to be doing that.
In each row, you have to, first, print the year (starting with the current year) up until the maximum year. Making the first for loop iterate over the years is a good choice (i.e. making i go from 2018 until maxYears + 2018). Second, you have to print the speed for each year after calculating the improvement via the provided equation. (I'm assuming that in the problem description it was given that the first speed is 10000? If not, what is the starting value?) Because you will only print a number, you don't need a second for loop. Just calculate the new speed and print it. As for the third and fourth column, I'm not sure what is asked exactly, so for now it will be blank in the code.
I modified code based on my comments, plus a few other modifications related to my understanding of the problem description, coding best practices, and stylistic choices (read below the code for more info on why).
#include <iostream>
//--1
int main()
{
//--2
const float speedLight = 299792;
const int startingYear = 2018;
//--3
float percentIncrease = 0;
while ((percentIncrease <= 0) || (percentIncrease >= 100))
{
std::cout << "What percentage do rocket speeds increase by each year?" << std::endl;
std::cin >> percentIncrease;
}
//--4
int maxYears = -1;
while (maxYears < 1)
{
std::cout << "What is the maximum number of years you are willing to wait on earth before you leave? " << std::endl;
std::cin >> maxYears;
}
std::cout << "Year|\tAvg Speed|\tEarth ETA|\tYour ETA" << std::endl;
//--5
float currentSpeed = 10000;
for (int year = startingYear; year <= (maxYears + startingYear); ++year)
{
//--6
std::cout << year << "\t" << currentSpeed << std::endl;
currentSpeed = currentSpeed + (speedLight - currentSpeed) * (percentIncrease / 100);
}
//--7
system("pause");
return 0;
}
--1: I removed unused libraries. (You may be using them for other parts
of the program, like if you want to print float numbers). I also
removed the using namespace std; because it is a bad practice. You
can google it.
--2: These numbers seem unchanging, so it is better to make them
constants.
--3: Maybe percentIncrease is not necessarily an integer.
--4: The problem description states that the number of years is a
positive integer, so it cannot be 0.
--5: The currentSpeed (previously j) should be defined outside the
loop because it will be updated inside the loop. Plus, it is a float
because of #3.
--6: The speed should be printed after the year.
--7: This is optional, in case you want the program window to not close
immediately. You can alternatively debug there by putting a
breakpoint, or any other solution.

C++ Long Division

Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.

C++ strings and arrays

I'm Having problems with to of the questions on my C++ homework.
Write a program to analyze gasoline price in the past 10 days. First, ask the user to enter the prices. Then do the following:
(a) Calculate and display the average price in the first 5 days and the average price in the second 5 days
(b) Compare the two average prices. Determine and report which one is higher (or they are the same).
(c) Compare each day’s price (except day 1) with the price the day before. Determine whether it became higher, lower or remained the same. Count and report the number of days the price was higher than, lower than and the same as the price the day before, respectively.
i'm not sure how to compare how to compare the first five days with the last five days, and part c I'm completely lost on....
i'm not looking for someone to do my homework for me, but a push in the right direction would be a great help!
here is what I have made so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
double gasPrice[10];
double firstFive = 0.0;
double lastFive = 0.0;
double ffAvg = 0.0;
double lfAvg = 0.0;
for (int x = 0; x < 10; x = x + 1)
{
gasPrice[x] = 0.0;
}
cout << "You will be asked to enter daily gas prices for 10 days."<< endl;
ofstream gasprice;
gasprice.open("gasprice.txt", ios::app);
if (gasprice.is_open())
{
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter the gas price " << x+1 << ": ";
getline(cin, gasPrice[x];
}
if ( ffAvg > lfAvg)
{
cout << "The first five days have a lower gas price " << ffAvg << lfAvg << endl;
}
else if ( ffAvg < lfAvg)
{
cout << "The last five days have a lower gas price " << ffAvg << lfAvg << endl;
}
system("pause ");
return 0;
}
Read the requirements like they are a description rather than a computer formula. It can become overwhelming when learning something for the first time and we get drowned by the things that would come natural in another environment.
Anyway, you are not to compare the days individually but an AVERAGE of the days. So you first need to compute the AVERAGE of the first five and the AVERAGE of the second five days, then compare that.
For the second part of your question, aggregators for your totals is the push I would give you.
Hope this helps.
Break down the problem in to a series of stages: Firstly, you need to get 10 input prices from the user, and store them in an array of size 10.
Next, you need to compute the average price for the first five days (i.e. for values in index 0-4 of your array), and store it in ffAvg, you can do this using the following simple for loop:
double sum;
for( int i = 0; i < 5; i++ )
{
sum += gasPrice[i];
}
double ffAvg = sum / 5;
You then do this with the 2nd 5 days, storing the average in lfAvg.
The next part of your task is to compare the averages, you can doing this using if and else if statements, for example, if you wanted to compare to numbers, num1 and num2 you might do the following:
if( num1 > num2 )
{ /* Do something */ }
This will compare num1 and num2 and if num1 is greater than num2 it will perform the code in the braces.
To do the last comparison you simply combine what we have done above on a per day basis. Try to experiment with various ways of doing it, as this will help you to learn more.
Hope this helps you! :)
EDIT: I also noticed that you've not closed a lot of your bracers, you must always do this so the compiler can work properly. Every { must have a corresponding }, else the compiler should throw up errors, and not compile.
I sugest doing as following:
double average1=0.0;
for(int i=0;i<5;++i) {
average1 += values[i];
}
average1/=5.0;
double average2=0.0;
for(int i=5;i<10;++i) {
average2 += values[i];
}
average2/=5.0;
Also, take a look at std::vector, it may help you in further exercises:
http://www.cplusplus.com/reference/stl/vector/
You should first compute the average of the first and last 5 days. The average is defined by the sum divided by the number of items. So your average will be (gasPrice[0] + gasPrice[1] + gasPrice[2] + gasPrice[3] + gasPrice[4]) / 5.0.
You should probably make this computation in a loop similar to the one you have for getting the input. The loop should only iterate 5 times.