Hey guys i have a bug that i am unable to detect. Kindly help me out. In this code i want to calculate a percentage but after the calculation there is a zero value store in the variable "percentage"
int _tmain(int argc, _TCHAR* argv[])
{
int total_marks, obtained_marks, percentage;
total_marks = 1100;
cout << "enters yours obtained marks"<<endl;
cin >> obtained_marks;
percentage = (obtained_marks / total_marks) * 100;
cout << "yours percentage =" << percentage;
if (percentage >= 60)
{
cout << "you have passed with first division";
}
cout << "yours pecentage is=" << percentage;
system("pause");
return 0;
}
Integer division truncates towards zero.
Given
int total_marks, obtained_marks, percentage;
and
percentage = (obtained_marks / total_marks) * 100;
if obtained_marks is less than total_marks, the value of (obtained_marks / total_marks) will be zero. In that case,
percentage = (obtained_marks / total_marks) * 100;
will also be zero.
Even
percentage = (obtained_marks / total_marks) * 100.0;
will be zero, because the value in the parenthesis is still zero.
One better way would be:
percentage = ( 100 * obtained_marks ) / total_marks;
obtained marks and total marks are integers so you are getting zero when you divide. Change your data types to float or double.
Related
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.
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 << " ";
Im having trouble with the function taylor2 not returning a value if i input anything over 2. If I enter 0-2 it outputs the correct value but anything over 2 and I just get a flashing underscore with no data returned.
void taylor2(double x)
{
double total = 1;
int i = 0;
int count = 1;
double temp = 1;
do
{
{
if (i % 2 == 1)
{
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total += temp;
}
else {
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total -= temp;
}
}
count++;
i++;
} while (fabs(temp) >= .0001);
cout << "The last recoreded temporary value was: "<<temp << endl;
cout << "The computed value for cosine is : "<< total << endl;
cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
cout << endl;
}
I suspect that factorial is returning an int. If int is 32 bit (very common), then factorial will overflow once the argument reaches 13 (i = 5 in your case). Signed integer overflow is undefined behaviour in C++.
You could use a std::uint64_t (an unsigned 64 bit integer). This will allow you to evaluate a few larger factorials.
For more reference, see Calculating large factorials in C++
Better still, use a recurrence relation between your Taylor terms.
I am having trouble rounding a GPA double to 2 decimal places. (ex of a GPA needed to be rounded: 3.67924) I am currently using ceil to round up, but it currently outputs it as a whole number (368)
here is what I have right now
if (cin >> gpa) {
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
break;
} else {
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
using the above code with 3.67924 would output 368 (which is what I want, but just without the period between the whole number and the decimals). How can I fix this?
To round a double up to 2 decimal places, you can use:
#include <iostream>
#include <cmath>
int main() {
double value = 0.123;
value = std::ceil(value * 100.0) / 100.0;
std::cout << value << std::endl; // prints 0.13
return 0;
}
To round up to n decimal places, you can use:
double round_up(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::ceil(value * multiplier) / multiplier;
}
This method won't be particularly fast, if performance becomes an issue you may need another solution.
If it is just a matter of writing to screen then to round the number use
std::cout.precision(3);
std::cout << gpa << std::endl;
see
floating points are not exactly represented so by internally rounding the value and then using that in your calculations you are increasing the inexactness.
When you are trying to store values upto n decimal values in a variable .
You have to multiple that value with 10^n and divide the same with 10^n.
Afterward use type operator to manipulate in the program.
Here is the example : -
float a,b,c,d,sum;
cin>>a>>b>>c>>d; // reading decimal values
sum=(a*b*c*d);
sum=round(sum*100)/100; // here it is for 2 decimal points
if((float)sum < (float) 9.58)
cout<<"YES\n";
else
cout<<"NO\n";
You can't round doubles to two decimal places. Doubles don't have decimal places. They have binary places, and they aren't commensurable with decimal places.
If you want decimal places, you must use a decimal radix, e.g. when formatting for output with printf("%.2f", ...).
Try this. But your cout statement in else condition, so it won't give the desired output for 3.67924.
if (cin >> gpa)
{
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
gpa=gpa/100;
break;
}
else
{
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
Example: you want 56.899999999999 to be output as a string with 2 decimal point which is 56.89.
First, convert them
value = 56.89 * 1000 = 5689
factor = 100
- 1 decimal point = 10
- 2 decimal point = 100
- 3 decimal point = 1000
etc
int integerValue;
int decimal;
std::string result;
function ( int value , int factor)
{
integerValue= (value / factor) * factor; //(5689 / 100) * 100 = 5600
decimal = value - integerValue; // 5689 - 5600;
result = std::to_string((int)(value/factor) + "." + std::to_string(decimal);
// result = "56" + "." + "89"
// lastly, print result
}
Not sure if this can help?
std::string precision_2(float number)
{
int decimal_part = (number * 100) - ((int)number * 100);
if (decimal_part > 10) {
return std::to_string((int)number) + "." + std::to_string(decimal_part);
} else {
return std::to_string((int)number) + ".0" + std::to_string(decimal_part);
}
}
Handles well for all positive floats. A minor modification will make it work for -ves as well.
I am currently writing a program that estimates Pi values using three different formulas pictured here: http://i.imgur.com/LkSdzXm.png .
This is my program so far:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double leibniz = 0.0; // pi value calculated from Leibniz
double counter = 0.0; // starting value
double eulerall = 0.0; // pi value calculated from Euler (all integers)
double eulerodd = 0.0; // value calculated from Euler (odds)
int terms;
bool negatives = false;
cin >> terms;
cout << fixed << setprecision(12); // set digits after decimal to 12 \
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++;
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++;
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++;
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
if (terms < 0){
if(!negatives)
negatives=true;
cout << "There were " << negatives << " negative values read" << endl;
}
return 0;
}
The sample input file that I am using is:
1
6
-5
100
-1000000
0
And the sample output for this input file is:
1 4.000000000000 2.449489742783 3.174802103936
6 2.976046176046 2.991376494748 3.141291949057
100 3.131592903559 3.132076531809 3.141592586052
When I run my program all I get as an output is:
1 4.000000000000 1.224744871392 1.131370849898.
So as you can see my first problem is that the second and third of my equations are wrong and I can't figure out why. My second problem is that the program only reads the first input value and stops there. I was hoping you guys could help me figure this out. Help is greatly appreciated.
You have three problems:
First, you do not implement the Euler formulae correctly.
π2/6 = 1/12 + 1/22 + 1/32 + ...
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
The square root of the sum is not the sum of the square roots.
π3/32 = 1/13 + 1/33 + 1/53 + ...
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
This is just... wrong.
Second, you increment counter three times in the loop, instead of once:
while(terms > counter){
...
counter++;
...
counter++;
...
counter++;
...
}
Third, and most fundamental, you didn't follow the basic rule of software development: start small and simple, add complexity as little at a time, test at every step, and never add to code that doesn't work.
my first problem is that the second and third of my equations are
wrong and I can't figure out why
Use counter++ just once. Apart from this Leibniz looks fine.
Eulerall is not correct, you should sum all factors and then do sqrt and multiplication at the end:
eulerall = 1/pow(counter+1,2) + eulerall;
// do sqrt and multiplication at the end to get Pi
The similar thing with eulerodd: you should sum all factors and then do sqrt and multiplication at the end.
My second problem is that the program only reads the first input value
and stops there.
In fact this is your first problem. This is because you are incrementing counter multiple times:
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++; // << increment
^^^^^^^^^^
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++; // << increment
^^^^^^^^^^
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++; // << increment
^^^^^^^^^^
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
You should increment counter just once.
You're using the same counter and incrementing it after each calculation. So each technique is only accounting for every third term. You should increment counter only once, at the end of the loop.
Also note that it is generally bad form to use a floating-point value as a loop counter. It only takes on integer values in your program, so you can just make it an int. Nothing else needs to change; the math will run the same because the int will promote to a double when you combine the two in math operations.
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
char* main()
{
while(1)
{
int Precision;
float answer = 0;
cout<<"Enter your desired precision to find pi number : ";
cin>>Precision;
for(int i = 1;i <= Precision;++i)
{
int sign = (pow((-1),static_cast<float>(i + 1)));
answer += sign * 4 * ( 1 / float( 2 * i - 1));
}
cout<<"Your answer is equal to : "<<answer<<endl;
_getch();
_flushall();
system("cls");
}
return "That is f...";
}