I am learning to code, so please forgive me for asking such a rudimentary question (gotta start somewhere, right?) I have written the following C++ program which approximates an e^x series expansion (Taylor series).
The problem I have is with the output. One of the sample outputs I need to have is as follows:
Sample Run 5:
This program approximates e^x using an n-term series expansion.
Enter the number of terms to be used in the approximation of e^x-> 8
Enter the exponent(x)-> -0.25
e^-0.25000 = 1.00000 - 0.25000 + 0.03125 - 0.00260 + 0.00016 - 0.00001 + 0.00000 - 0.00000 = 0.77880
But my code creates the following output instead:
e^-0.25000 = 1.00000 + -0.25000 + 0.03125 + -0.00260 + 0.00016 + -0.00001 + 0.00000 + -0.00000 = 0.77880
Essentially, I am unsure how to represent these negative values dynamically, in order to match the desired output. At present, they are all represented by " + " string literals in my code, in between the recursive term that repeats.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int numTerms, i;
long double x, numer, denom, prevDenom, term, sum;
int main ()
{
cout << "This program approximates e^x using an n-term series expansion." << endl;
cout << "Enter the number of terms to be used in the approximation of e^x-> ";
cin >> numTerms;
cout << "Enter the exponent(x)-> ";
cin >> x;
cout << endl;
if (numTerms <= 0)
cout << numer << " is an invalid number of terms." << endl;
else if (numTerms == 1)
{
sum = 1.00000;
cout << "e^" << fixed << setprecision(5) << x << " = " << sum << " = " << sum << endl;
}
else
{
cout << "e^" << fixed << setprecision(5) << x <<" = " << 1.00000;
sum += 1.00000;
prevDenom = 1;
for (i = 1; i < numTerms; i++)
{
numer = pow(x,(i));
denom = (prevDenom) * (i);
term = numer / denom;
sum += term;
prevDenom = denom;
cout << " + " << term;
}
cout << " = " << fixed << setprecision(5) << sum << endl;
}
}
Thanks in advance!
You could replace:
cout << " + " << term;
with:
if (term >= 0)
cout << " + " << term;
else
cout << " - " << (-term);
So when a term is negative you print the minus sign yourself with the extra space you need and then you print the positive part of your term.
Related
I'm a fairly new to c++. I'm trying to create a very basic calculator and the results I'm getting are completely wrong. I've come to a standstill after 2 hours of trying everything in my knowledge. What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
float sum = 'a' + 'b';
float diff = 'a' - 'b';
float prod = 'a' * 'b';
float quot = 'a' / 'b';
float rem = 'a' % 'b';
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
you are calculating with character literals. 'a' is not the same as a here.
remove the quotes when calculating, but add them when you print the actual literal "a"
float sum = 'a' + 'b';
You are calculating the ASCII value of the character "a" (which is 65) with the ASCII value of "b" (which is 66)
It should be
float sum = a + b;
instead.
When you print the values, you did the reverse:
cout << a << " + " << b << " = " << sum <<endl;
You want it to be
cout << "a" << " + " << "b" << " = " << sum <<endl;
instead. You want to print characters for the equation and only a number for the result.
You also calculate the values of a and b before they have an actual value.
You should put the calculation after you enter them.
Fixed, by moving the calculations after the input; and by using variables, not literals.
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
float sum = a + b;
float diff = a - b;
float prod = a * b;
float quot = a / b;
float rem = a % b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
Using a Linear Congruent Generator I am able to create two independent Pseudo-Random number sequences which are uniformly distributed. I am trying to alter my program to allow it to use these sequences and perform a Box-Muller transform to change them into a normally distributed set.
The issue I am having however is that my new "normally distributed random number" (Z) is always equal to zero regardless of the input seed values for the two uniform sequences.
Any tips would be gratefully appreciated.
Many Thanks
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
#define M 4294967295
unsigned long get_rand(unsigned long x) //establishing function to generate random numbers
{
unsigned long a = 2269477;
unsigned long b = 1; //Values taken from wikipedia for Linear Congruence Method
unsigned long m = M;
unsigned long y;
y = (a * x + b) % m;
return y;
}
unsigned long get_normal(unsigned long x1, unsigned long x2)
{
unsigned long R;
unsigned long phi;
unsigned long u;
R = sqrt(-2 * log(x1)); //Box-Muller Transform
phi = (2 * M_PI*x2);
u = R*cos(phi);
return u;
}
double u1, u2, Z;
double bin0 = 0;
double bin1 = 0;
double bin2 = 0; //Variables used to store frequency of each number range
double bin3 = 0;
double bin4 = 0;
double bin5 = 0;
double bin6 = 0;
double bin7 = 0;
double bin8 = 0;
double bin9 = 0;
int main() {
double seed1,seed2;
cout << "Please enter seed values " << endl;
cin >> seed1;
cout << "\n";
cin >> seed2;
double x;
cout << "Please enter how many random numbers you want " << endl;
cin >> x;
cout << endl;
cout << "Random Numbers generated shown below: " << endl;
for (int i = 0; i < x; i++) //generate as many random numbers as the user has asked for
{
seed1 = get_rand(seed1);
seed2 = get_rand(seed2);
u1 = (double(seed1) / M); //changing to double and dividing by 'M' gets all values between 0 and 1
cout <<"U1 = " << u1 << endl; //type conversion to prevent integer rounding in division
u2 = (double(seed2) / M);
cout << "U2 = " << u2 << endl;
Z = get_normal(u1, u2);
cout <<"Z = " << Z << endl;
if (Z >= 0.0 && Z <= 0.1)
{ //checking for which intervals each random number falls into
bin0++; //if a number falls into this interval, increment the counter by 1 each time
}
else if (Z > 0.1 && Z <= 0.2) //if it doesnt fall into first interval, it will check the next interval, and so on...
{
bin1++;
}
else if (Z > 0.2 && Z <= 0.3)
{
bin2++;
}
else if (Z > 0.3 && Z <= 0.4)
{
bin3++;
}
else if (Z > 0.4 && Z <= 0.5)
{
bin4++;
}
else if (Z > 0.5 && Z <= 0.6)
{
bin5++;
}
else if (Z > 0.6 && Z <= 0.7)
{
bin6++;
}
else if (Z > 0.7 && Z <= 0.8)
{
bin7++;
}
else if (Z > 0.8 && Z <= 0.9)
{
bin8++;
}
else if (Z > 0.9 && Z <= 1.0)
{
bin9++;
}
}
double binTotal = bin0 + bin1 + bin2 + bin3 + bin4 + bin5 + bin6 + bin7 + bin8 + bin9;
cout << endl;
int bin0Percent = (bin0 / binTotal) * 100; //working out a percentage
cout << " Number of values in range 0.0-0.1: " << bin0 << endl; //output screen for each interval
cout << " Percentage of values in this interval: " << bin0Percent << "%" << endl;
cout << endl;
int bin1Percent = (bin1 / binTotal) * 100;
cout << " Number of values in range 0.1-0.2: " << bin1 << endl;
cout << " Percentage of values in this interval: " << bin1Percent << "%" << endl;
cout << endl;
int bin2Percent = (bin2 / binTotal) * 100;
cout << " Number of values in range 0.2-0.3: " << bin2 << endl;
cout << " Percentage of values in this interval: " << bin2Percent << "%" << endl;
cout << endl;
int bin3Percent = (bin3 / binTotal) * 100;
cout << " Number of values in range 0.3-0.4: " << bin3 << endl;
cout << " Percentage of values in this interval: " << bin3Percent << "%" << endl;
cout << endl;
int bin4Percent = (bin4 / binTotal) * 100;
cout << " Number of values in range 0.4-0.5: " << bin4 << endl;
cout << " Percentage of values in this interval: " << bin4Percent << "%" << endl;
cout << endl;
int bin5Percent = (bin5 / binTotal) * 100;
cout << " Number of values in range 0.5-0.6: " << bin5 << endl;
cout << " Percentage of values in this interval: " << bin5Percent << "%" << endl;
cout << endl;
int bin6Percent = (bin6 / binTotal) * 100;
cout << " Number of values in range 0.6-0.7: " << bin6 << endl;
cout << " Percentage of values in this interval: " << bin6Percent << "%" << endl;
cout << endl;
int bin7Percent = (bin7 / binTotal) * 100;
cout << " Number of values in range 0.7-0.8: " << bin7 << endl;
cout << " Percentage of values in this interval: " << bin7Percent << "%" << endl;
cout << endl;
int bin8Percent = (bin8 / binTotal) * 100;
cout << " Number of values in range 0.8-0.9: " << bin8 << endl;
cout << " Percentage of values in this interval: " << bin8Percent << "%" << endl;
cout << endl;
int bin9Percent = (bin9 / binTotal) * 100;
cout << " Number of values in range 0.9-1.0: " << bin9 << endl;
cout << " Percentage of values in this interval: " << bin9Percent << "%" << endl;
cout << endl;
}
get_normal returns a long, which cannot be between 0 and 1, since it is an integer. Storing the integer returned by the function into a double (Z) does not magically restore the discarded fractional part.
I think you should use floating point arithmetic (that is, doubles) in get_normal, and also change the return type.
By the way, the C++ standard library has lots of random number distributions. You might want to use it instead of trying to write your own.
M is too big, in the limit of a long. So any long divided (or modulus) by this M will result in 0. Perphaps you should use unsigned long long.
Also:
Instead of R = sqrt(-2 * log(x1)); try R= sqrt(fabs(2 * log(x1)));
Also
phi = (2 * M_PI*x2);
u = R*cos(phi);
phi is always an multiple of 2*PI, so cos(phi)= 1.
I made a simple program to add and subtract the given numbers. Let's say the 2 numbers give were 5 and 5. It would print 5 + 5 = 10 and 5 - 5 = 0. Right now I'm not sure what's wrong. I might need a temporary variable, but something with the input isn't right. If you test the numbers with 5 and 5 it prints:
Addition / Subtraction Program
*------------------------------*
Press Enter to begin!
What is the number you'd like to add / sub to?5
5
What is the next number?5
55 + 5 = 105 - 5 = 0
Here's the code I'm using:
#include <iostream>
using namespace std;
int main() {
int num_1;
int num_2;
cout << "Addition / Subtraction Program" << endl << "*------------------------------*\n\nPress Enter to begin!";
cin.get();
cout << "What is the number you'd like to add / sub to?";
cin >> num_1;
cout << num_1 << endl << "What is the next number?";
cin >> num_2;
cout << num_2;
cout << num_1 << " + " << num_2 << " = " << num_1 + num_2;
cout << num_1 << " - " << num_2 << " = " << num_1 - num_2;
return 0;
}
The output is correct, it's just missing spaces.
After the user enters their number, you echo it back to them; without any whitespace. This "turns" 5 into 55, and 10 5 into 105.
The addition and subtraction are fine, you just need to format your output. End your cout lines with a << endl; or << "\n"; to see the difference.
The outputs are not incorrect. You only need to fix the formatting. In between the following two cout's, there is no clear demarcation:
cout << num_1 << " + " << num_2 << " = " << num_1 + num_2;//cout 1
cout << num_1 << " - " << num_2 << " = " << num_1 - num_2;//cout 2
Hence you get the output as:
55 + 5 = 105 - 5 = 0
|-cout 1 -||-cout 2-|
You can either use a newline (by cout<<endl; or cout<<"\n"; between the two) or a space(cout<<" ";) to clearly demarcate between the two outputs.
Actually there is no problem with addition and subtraction. You didn't print the new line ('\n') character at the end of this line -
cout << num_1 << " + " << num_2 << " = " << num_1 + num_2;
It's good practice to add newline ('\n') character one endl manipulator at the end of each line.
In your current code, you have only formatting problem.
This is my code. The information my professor gave us to only show 2 decimal points is out.precision(2) ;.
cout << "Welcome to the Book Store" << endl << endl;
cout << "Enter the single copy price: $" ;
cin >> single_copy_price ;
cout << "Enter the number of books sold: " ;
cin >> num_of_books_sold ;
cout << "Enter the discount percentage: " ;
cin >> discount_percentage ;
cout << "********************************************" << endl ;
subtotal = single_copy_price * num_of_books_sold ;
cout.precision(2) ;
cout<< "Subtotal: $" << subtotal << endl ;
cout << "Discount percentage: " << discount_percentage << "%" << endl ;
discount_ammount = subtotal * (discount_percentage / 100) ;
cout.precision(2) ;
cout << "Discount ammount: $ " << discount_ammount << endl ;
cout.precision(2) ;
cout << "Final price: $" << subtotal - discount_ammount << endl ;
return 0;
`
However, this is my result:
Welcome to the Book Store
Enter the single copy price: $10.50
Enter the number of books sold: 20
Enter the discount percentage: 15
Subtotal: $2.1e+02
Discount percentage: 15%
Discount ammount: $ 32
Final price: $1.8e+02
Program ended with exit code: 0
Thank you for the help!
The problem is the cout.setprecision(2). What it does is limit the number of significant figures in a number displayed. It's useful for scientific work, but not what you are looking for.
One person's solution was to write their own formatting method: http://www.arachnoid.com/cpptutor/student3.html
At the very end is point 6, for currency. His solution also formats with $ and commas for thousands places.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void showCurrency(double dv, int width = 14)
{
const string radix = ".";
const string thousands = ",";
const string unit = "$";
unsigned long v = (unsigned long) ((dv * 100.0) + .5);
string fmt,digit;
int i = -2;
do {
if(i == 0) {
fmt = radix + fmt;
}
if((i > 0) && (!(i % 3))) {
fmt = thousands + fmt;
}
digit = (v % 10) + '0';
fmt = digit + fmt;
v /= 10;
i++;
}
while((v) || (i < 1));
cout << unit << setw(width) << fmt.c_str() << endl;
}
The most simple solution is to set your precision to 2 more than the number of digits in the integer portion. To figure that out, cast to int and count the number of times you can divide by 10 with a non-zero result.
I'm learning C++, and to do that I have created myself a problem which is to convert Celsius to Fahrenheit three times in the console. The user will input the Celsius degree.
I also want the output to be displayed like this:
Celsius: Fahrenheit:
cel1 fahr1
cel2 fahr2
cel3 fahr3
The code I have tried so far is:
double cel1, cel2, cel3;
double fahr1, fahr2, fahr3;
cout << "Celsius degree one: ";
cin >> cel1;
cout << "Celsius degree two: ";
cin >> cel2;
cout << "Celsius degree three: ";
cin >> cel3;
fahr1 = (cel1 * 9) / 5 + 32;
fahr2 = (cel2 * 9) / 5 + 32;
fahr3 = (cel3 * 9) / 5 + 32;
// messy like this to display like I want to
cout << endl <<
"Celsius: " << "Fahrenheit:" << endl <<
cel1 << " " << fahr1 << endl <<
cel2 << " " << fahr2 << endl <<
cel3 << " " << fahr3 << endl << endl;
which will display like I want to, but I feel this could have been achieved in a simpler way, so I tried something like this with a loop, but I couldn't figure out how to do it properly:
double celsius;
for (int times = 0; times != 3; ++times){
cout << "Celsius degree: ";
cin >> celsius;
double fahrenheit = (celsius * 9) / 5 + 32;
cout << "Fahrenheit degree: " << fahrenheit << endl;
cin.clear();
}
This code is less then the previous one, gives the correct answer and will convert three times, but I couldn't figure out how to display it like I want to.
My question is what is the best way to do this?
I suggest to split the code into smaller functions:
The one to compute the conversion
double celsius_to_fahrenheit(double celsius)
{
return (celsius * 9.0) / 5.0 + 32.0;
}
The one to get the input, I choose to use std::vector as container.
you may choose std::array<double, 3> since the array have fixed size,
but std::vector is a good default choice.
std::vector<double> get_input_celsius(std::size_t size)
{
std::vector<double> celsius(size);
for (std::size_t i = 0; i != celsius.size(); ++i) {
std::cout << "Celsius degree " << (i + 1) << ": ";
std::cin >> celsius[i];
}
return celsius;
}
The method to display the result. I choose to not store the conversion in a new std::vector since it is not used afterward:
void display_celsius_and_fahrenheit(const std::vector<double>& celsius)
{
std::cout << std::endl << "Celsius: " << "Fahrenheit:" << std::endl;
for (auto c : celsius) { // for range since C++11
std::cout << c << " " << celsius_to_fahrenheit(c) << std::endl;
}
}
And finally the main function:
int main()
{
std::vector<double> celsius = get_input_celsius(3);
display_celsius_and_fahrenheit(celsius);
return 0;
}
Live example
Create arrays to store the temperatues.
Instead of
double cel1, cel2, cel3;
double fahr1, fahr2, fahr3;
use
double celsius[3];
double fahrenheit[3];
Change the input gathering loop to use the arrays.
for (int times = 0; times != 3; ++times){
cout << "Celsius degree: ";
cin >> celsius[times];
fahrenheit[times] = (celsius[times] * 9) / 5 + 32;
cin.clear();
}
Use a loop to create the output:
cout << endl << "Celsius: " << "Fahrenheit:" << endl <<
for (int times = 0; times != 3; ++times){
cout << celsius[times] << " " << fahrenheit[times] << endl;
}
You could get away with not creating the array fahrenheit too if you compute it only during output.
In that case, change the input gathering loop to:
for (int times = 0; times != 3; ++times){
cout << "Celsius degree: ";
cin >> celsius[times];
cin.clear();
}
Change the output loop to:
cout << endl << "Celsius: " << "Fahrenheit:" << endl <<
for (int times = 0; times != 3; ++times){
double fahrenheit = (celsius[times] * 9) / 5 + 32;
cout << celsius[times] << " " << fahrenheit << endl;
}