A puzzle on an beginner's program - c++

I wrote this dumb little program after watching about an hour of C++ tutorial. It is garbage, but it produced a really weird error that a few software engineers haven't been able to solve, so now it's interesting to us.
It is supposed to spit out binomials and trinomials, and then give the derivative for the trinomials. The dollar signs are there to help me copypasta into LaTeX.
EDIT: The exact error in the output is it's posting:
"inear equations do you need?-12x+8$"
instead of
"Derivative= "
Thanks for the comment.
A /highfive for anyone who figures out why the output is so weird.
The output:
How many sets of 3 linear equations do you need?
2
How many sets of 3 quadratics do you need?
2
12x-3
-3x+12
-5x-9
15x-5
-5x+15
-4x-2
$8x^2-15x-6$
inear equations do you need?16x-15$
$-15x^2-6x+8$
inear equations do you need?-30x-6$
$-6x^28x-15$
inear equations do you need?-12x+8$
$2x^2-13x-2$
inear equations do you need?4x-13$
$-13x^2-2x+2$
inear equations do you need?-26x-2$
$-2x^22x-13$
inear equations do you need?-4x+2$
$11x^2-3x-13$
inear equations do you need?22x-3$
$-3x^2-13x+11$
inear equations do you need?-6x-13$
$-13x^211x-3$
inear equations do you need?-26x+11$
Press any key to continue . . .
The Code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
/*Simple Function maker*/
using namespace std;
void polynomial(string numberOfPolys)
{
/*AX^2+BX+C format*/
for (int i = 0; i <= (std::stoi(numberOfPolys, 0)); i++) {
int a = (rand() % 15) + 1;
int b = -1 * ((rand() % 15) + 1);
int c = -1 * ((rand() % 15) + 1);
int d = -1 * ((rand() % 15) + 1);
string problemWriter = '$' + to_string(a) + 'x' + '^' + '2' + to_string(b) + 'x' + to_string(c) + '$';
string problemWriter2 = '$' + to_string(b) + 'x' + '^' + '2' + to_string(c) + 'x' + '+' + to_string(a) + '$';
string problemWriter3 = '$' + to_string(c) + 'x' + '^' + '2' + to_string(a) + 'x' + to_string(b) + '$';
string answerWriter = "Derivative= " + '$' + to_string(a * 2) + 'x' + to_string(b) + '$';
string answerWriter2 = "Derivative= " + '$' + to_string(b * 2) + 'x' + to_string(c) + '$';
string answerWriter3 = "Derivative= " + '$' + to_string(c * 2) + 'x' + '+' + to_string(a) + '$';
cout << problemWriter << endl;
cout << answerWriter << endl;
cout << problemWriter2 << endl;
cout << answerWriter2 << endl;
cout << problemWriter3 << endl;
cout << answerWriter3 << endl;
}
}
int main()
{ /*MX+B format*/
string input;
string polys;
cout << "How many sets of 3 linear equations do you need?" << endl;
getline(cin, input);
cout << "How many sets of 3 quadratics do you need?" << endl;
getline(cin, polys);
for (int i = 0; i < (std::stoi(input, 0)); i++) {
int f = (rand() % 15) + 1;
int g = -1 * ((rand() % 15) + 1);
int h = -1 * ((rand() % 15) + 1);
int k = -1 * (rand() % 15) + 1;
string problemLWriter = to_string(f) + 'x' + to_string(g);
string problemLWriter2 = to_string(g) + 'x' + '+' + to_string(f);
string problemLWriter3 = to_string(h) + 'x' + to_string(k);
cout << problemLWriter << endl;
cout << problemLWriter2 << endl;
cout << problemLWriter3 << endl;
}
polynomial(polys);
return 0;
}

The problem is with the lines when you create the answerWriter strings:
string answerWriter = "Derivative= " + '$' + to_string(a * 2) + 'x' + to_string(b) + '$';
"Derivative= " is a character array, not a string. You cannot concatenate characters to it.
Change it to this:
string answerWriter = string("Derivative")+ '$' + to_string(a * 2) + 'x' + to_string(b) + '$';

Related

Deleting words from a string and printing their addresses

The task is to delete all repeating words from the string and then print the addresses of these words (meaning the addresses of the first letters) in the original string on the screen.
My code looks like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string inputString = "cactus word programmer cat word dog cat. cat mug words.";
inputString += ' ';
string copiedString = inputString;
string word;
int wordSize = 0;
int startIndex = 0;
for (size_t i = 0; i < copiedString.size(); i++)
{
if (copiedString[i] == ' ' || copiedString[i] == '.')
{
//startIndex = i;
word.insert(0, copiedString, startIndex, wordSize);
while (copiedString.find(' ' + word + ' ', startIndex + wordSize) != -1 ||
copiedString.find(' ' + word + '.', startIndex + wordSize) != -1)
{
string *address = (inputString.find(word, startIndex + wordSize) + &inputString);
cout << *address << '\t' << address << endl;
copiedString.erase(copiedString.find(word, startIndex + wordSize), wordSize + 1);
}
while (copiedString.find(' ' + ' ') != -1)
{
copiedString.erase(copiedString.find(' ' + ' ', 1));
}
word.clear();
wordSize = 0;
startIndex = i + 1;
}
else
wordSize++;
}
cout << inputString << endl;
cout << copiedString << endl;
return 0;
}
So I tried to make it work with both dots and spaces. For that I needed a loop which deletes all
unnecessary spaces (the second while loop). The program doesn't delete spaces, however, and throws some exceptions saying I'm trying to access wrong part of the memory (I think) and it prints incorrect addresses (last 2 repeat for some reason).
Ended up rewriting the whole thing but this is what I came up with:
int main()
{
string inputString = "cactus. word programmer cat word dog cat. cat. cat mug words. words. abc abcde abba programmer";
inputString = inputString + ' ';
string copiedString = inputString;
string word;
int wordSize = 0;
int startIndex = 0;
for (size_t i = 0; i < copiedString.size(); i++)
{
if (copiedString[i] == ' ' || copiedString[i] == '.')
{
word.insert(0, copiedString, startIndex, wordSize);
int k = 0;
while (copiedString.find(' ' + word + ' ', startIndex + wordSize) != -1)
{
const size_t currentIndex = inputString.find(' ' + word + ' ', startIndex + wordSize);
cout << word;
if (wordSize >= 7)
cout << '\t';
else
cout << "\t\t";
cout << (inputString.find(' ' + word + ' ', currentIndex + k * wordSize) + &inputString) << endl;
copiedString.erase(copiedString.find(' ' + word + ' ', startIndex + wordSize), wordSize + 1);
k++;
}
k = 0;
while (copiedString.find(' ' + word + '.', startIndex + wordSize) != -1)
{
const size_t currentIndex = inputString.find(' ' + word + '.', startIndex + wordSize);
cout << word;
if (wordSize >= 7)
cout << '\t';
else
cout << "\t\t";
cout << (inputString.find(' ' + word + '.', currentIndex + k * wordSize) + &inputString) << endl;
copiedString.erase(copiedString.find(' ' + word + '.', startIndex + wordSize), wordSize + 2);
k++;
}
word.clear();
wordSize = 0;
startIndex = i + 1;
}
else
wordSize++;
}
cout << endl << inputString << endl;
cout << copiedString << endl;
return 0;
}

Accelerated C++ Exercise 2.4

I've been following Accelerated C++ for a couple of weeks now but I have been stuck at exercise 2.4 for a while and finally I thought I found it out but after trying giving it different dimensions I found out that it doesn't really work and I don't really understand why
The code initially prints a framed message, in this particular exercises I was supposed to change how the code prints the blanks from one character at a time into writing all the planks at once
here is the code:
// [2-0, 2-4] Exercises
#include<iostream>
#include<string>
// saying what standard-library names we use
using std::cout; using std::endl;
using std::cin; using std::string;
int main()
{
// asking for the name
cout << "Please enter your first name: ";
// reading the name
string name;
cin >> name;
// building the message that we intend to write
const string greeting = "Hello, " + name + "!";
// 2.2 & 2.3 asking for inpadY
cout << "Please enter the number of padY (Vertical padding): ";
// 2.2 & 2.3 reading the inpadY
int inpadY;
cin >> inpadY;
// 2.2 & 2.3 asking for inpadX
cout << "Please enter the number of padX (Horizontal padding): ";
// 2.2 & 2.3 reading the inpadX
int inpadX;
cin >> inpadX;
// the number of planks surrounding the greeting
// 2.2 & 2.3 added inpadY as the number of planks;
const int padY = inpadY;
// 2.2 & 2.3 added inpadX
const int padX = inpadX;
// 2.4 pad size
const int pad = inpadX + inpadY;
// the number of rows and columns to write
const int rows = padY * 2 + 3;
const string::size_type cols = greeting.size() + padX * 2 + 2;
// 2.4 creating a padding string left and right and top and bottom
const string LeftRightPad(padY, ' ');
const string TopBottomPad(cols - 2, ' ');
// write a blank line to separate the output and the input
cout << endl;
// write rows rows of output
// invariant: we have written r rows so far
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
// invariant: we have written c characters so far in the current row
while (c != cols) {
// is it time to write the greeting?
if (r == padY + 1 && c == padX + 1)
{
cout << greeting;
c += greeting.size();
} else {
// are we on the border?
if (r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
{cout << "*";
++c;}
else
// 2.4 typing out the spaces at once
{cout << LeftRightPad;
c += LeftRightPad.size();}
}
}
cout << endl;
}
return 0;
}
Edited to have the input and output
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 2
Please enter the number of padX (Horizontal padding): 2
**********************
* *
* *
* Hello, Estrogen! *
* *
* *
**********************
Process returned 0 (0x0) execution time : 3.281 s
Press any key to continue.
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 2
Please enter the number of padX (Horizontal padding): 5
****************************
* *
* *
* *
* *
* *
****************************
Process returned 0 (0x0) execution time : 5.098 s
Press any key to continue.
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 3
Please enter the number of padX (Horizontal padding): 2
**********************
*
*
*
*
*
*
*
**********************
Process returned 0 (0x0) execution time : 4.333 s
Press any key to continue.
Update: I've rewritten the code and the output is an infinite loop of asterisks here is the new code
#include<iostream>
#include<string>
using std::string; using std::endl;
using std::cout; using std::cin;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
const string message = "Hello, " + name + "!";
cout << "Enter the length: ";
int length;
cin >> length;
cout << "Enter the height: ";
int height;
cin >> height;
const int rows = height * 2 + 3;
const string::size_type cols = message.size() + length * 2 + 2;
const string TopBottom(cols, '*');
const string Blank(cols - 2, ' ');
const string messageblank(cols - 3 - message.size(), ' ');
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if ( r == height + 1 && c == length + 1)
{
cout << messageblank << message << messageblank;
c += Blank.size();
} else
if (r == 0 && c == 0 || r == rows - 1 && c == cols -1)
{
cout << TopBottom;
c += TopBottom.size();
} else
if ( r != 0 && c == 0 || r != rows -1 && c == cols - 1)
{
cout << "*";
++c;
} else
cout << Blank;
c += Blank.size();
}
cout << endl;
}
return 0;
}
Thank you guys for help in advance
Unless the code is supposed to be written this way, I would propose another, row by row approach:
print_frame_row(cols);
for (int i = 0; i < padY; ++i)
print_v_padding(cols);
print_greeting(padX, greeting);
for (int i = 0; i < padY; ++i)
print_v_padding(cols);
print_frame_row(cols);
where
void print_frame_row(int cols)
{
std::cout << std::string(cols, '*') << '\n';
}
void print_v_padding(int cols)
{
const std::string h_padding(cols - 2, ' ');
std::cout << '*' << h_padding << "*\n";
}
void print_greeting(int padX, const std::string &msg)
{
const std::string h_padding(padX, ' ');
std::cout << '*' << h_padding << msg << h_padding << "*\n";
}
This way you have a simpler logic, and need not worry about counting columns or deciding when to write each character.
ok so it took me 3 days but I finally figured it out here is the working code
#include<iostream>
#include<string>
using std::string; using std::endl;
using std::cout; using std::cin;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Enter the length: ";
int length;
cin >> length;
cout << "Enter the height: ";
int height;
cin >> height;
const string message = "Hello, " + name + "!";
const int rows = height * 2 + 3;
const string::size_type cols = message.size() + length * 2 + 2;
const string TopBottom(cols, '*');
const string Blank(cols - 2, ' ');
const string messageblank(length, ' ');
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if ( r == height + 1 && c == 0)
{
cout << "*" << messageblank << message << messageblank << "*";
c += TopBottom.size();
} else
if (r == 0 && c == 0 || r == rows - 1 && c == 0)
{
cout << TopBottom;
c += TopBottom.size();
} else
if ( c == 0 && r != 0 || c == 0 && r != rows - 1)
{
cout << "*" << Blank << "*";
c += TopBottom.size();
}
}
cout << endl;
}
return 0;
}

Combined conversion

I just started to study informatics. Now i got my first task and i,am full of questions. Does someone have some advice for me?
The task is to create an math formula which allows to decide between 3 different formula without any kind of "switch, if-else or other operators"
Sooo goal is it to just
cin a number;
decide with cin 1, 2 or 3 between Celsius to Fahrenheit, meters in foot or € in $ and gettin a result. Im pretty new and just asking me for like 2 hours what such a formula would look like D:
any idea?
My Actual Code looks like this. (we arent allowed to use any kind of code we hadnt in our lectures yet. Allowed are just: value assignment, variables, simply data types , basic calculus, cins and couts..
Im just curious on that formula which does not get into my head and how to code it...
#include <iostream>
using namespace std;
int main()
{
double eingabe;
int auswahl = 0;
double ergebnis;
//zahleneingabe
cout << "Ihre Eingabe: ? " << endl;
cin >> eingabe;
cout << "Ihre Eingabe: " << eingabe << endl;
system("PAUSE");
//abfragenausgabe der umrechnungsart
cout << "Ihre Auswahl der Umwandlung: " << endl;
cout << "1 - Celsius in Fahrenheit" << endl;
cout << "2 - Meter in Fuss" << endl;
cout << "3 - Euro in US Dollar " << endl;
cin >> auswahl;
cout << "Ihr Ergebnis ist: " << ergebnis << endl;
system("PAUSE");
}
If Yasir's solution still uses features that aren't to your teacher's liking (operator == might be forbidden as well), the remaining solution is polynomial regression...
#include <iostream>
int main()
{
//zahleneingabe
std::cout << "Ihre Eingabe: ?\n";
double eingabe;
std::cin >> eingabe;
std::cout << "Ihre Eingabe: " << eingabe << '\n';
//abfragenausgabe der umrechnungsart
std::cout << "Ihre Auswahl der Umwandlung:\n";
std::cout << "1 - Celsius in Fahrenheit\n";
std::cout << "2 - Meter in Fuss\n";
std::cout << "3 - Euro in US Dollar\n";
int auswahl;
std::cin >> auswahl;
// Found using http://www.xuru.org/rt/PR.asp (ain't nobody got time for that)
double const coefficient = (-1.82584 * auswahl + 6.95836) * auswahl - 3.33252;
double const offset = (16.0 * auswahl - 80.0) * auswahl + 96.0;
double const ergebnis = eingabe * coefficient + offset;
std::cout << "Ihr Ergebnis ist: " << ergebnis << '\n';
}
Note that I have also cleaned up the code by removing using namespace std;, rescoping variables to their actual use, and added const where relevant. I leave it to you to translate the new variables to german ;)
See it live on Wandbox
You could also use modulo to your advantage.
Assume the formulae:
const float fahrenheitConst = 9.f/5.f;
const float feetConst = 3.2f;
const float exchangeRate = 1.11f;
// eingabe = x, auswahl = y
double a = x * fahrenheitConst + 32;
double b = x * feetConst;
double c = x * exchangeRate;
double result = ( y % 3 ) * ( y % 2 ) * a + ( ( y + 2 ) % 3 ) * ( y + 1 ) % 2 * b + ( y + 1 ) % 3 * ( ( y - 1 ) / 2 ) * c
Explanation
Basically we want a formula, that is a sum of three terms, where each term is the result of a subformula and two coefficients. For every input, the coefficients for one of the three terms must result in 1 each, while the coefficients for the other two terms must include at least one 0 coefficient per term. To put differently, we want only one of the three subformulae a, b or c to be part of result and its magnitude needs to be exactly 1.
y % 3 results in 0 for 3 and in 1 for 1
y % 2 results in 0 for 2 and in 1 for 1
( y + 2 ) % 3 results in 0 for 1 and in 1 for 2
( y + 1 ) % 2 results in 0 for 3 and in 1 for 2
( y + 1 ) % 3 results in 0 for 2 and in 1 for 3
( ( y - 1 ) / 2 ) results in 0 for 1 and in 1 for 3 (cannot use % 1)
Demonstration
Let input be 1:
result = ( 1 % 3 ) * ( 1 % 2 ) * a + ( ( 1 + 2 ) % 3 ) * ( 1 + 1 ) % 2 * b + ( 1 + 1 ) % 3 * ( ( 1 - 1 ) / 2 ) * c
= 1 * 1 * a + 0 * 0 * b + 1 * ( 0 / 2 ) * c
= 1 * a + 0 * b + 0 * c
= a
Let input be 2:
result = ( 2 % 3 ) * ( 2 % 2 ) * a + ( ( 2 + 2 ) % 3 ) * ( 2 + 1 ) % 2 * b + ( 2 + 1 ) % 3 * ( ( 2 - 1 ) / 2 ) * c
= 1 * 0 * a + 1 * 1 * b + 0 * [1/2 --> 0 in INT] * c
= 0 * a + 1 * b + 0 * c
= b
Let input be 3:
result = ( 3 % 3 ) * ( 3 % 2 ) * a + ( ( 3 + 2 ) % 3 ) * ( 3 + 1 ) % 2 * b + ( 3 + 1 ) % 3 * ( ( 3 - 1 ) / 2 ) * c
= 0 * 1 * a + 2 * 0 * b + 1 * 1 * c
= 0 * a + 0 * b + 1 * c
= c
Notes
There is an ambiguity in the division, that depends on the types used, this is where I wrote [1/2 --> 0 in INT]. That is because for float or double this results in 1/2, but for int this results in 0. Please note how this makes absolutely no difference here. The result could be 5000, but as long as the previous factor results in 0, the whole term resolves to 0.
Additionally you could use integer division to your advantage, i.e. dividing a smaller numer by a larger number will result in 0 for int . I chose not to go that way, because OP mentioned a mathematical solution, while taking advantage of integer division is rather a programmatical approach.
Conclusion
Use:
result = c1 * c2 * formula1 + c3 * c4 * formula2 + c5 * c6 * formula3
So that only the coefficients c_i for one of the three formulae resolve to exactly 1 each, while for the other coefficients at least one per formula must resolve in 0.
I think this should solve your problem. I can't think of anything else that solves it.
#include <iostream>
using namespace std;
int main()
{
double eingabe;
int auswahl = 0;
double ergebnis;
//zahleneingabe
cout << "Ihre Eingabe: ? " << endl;
cin >> eingabe;
cout << "Ihre Eingabe: " << eingabe << endl;
//abfragenausgabe der umrechnungsart
cout << "Ihre Auswahl der Umwandlung: " << endl;
cout << "1 - Celsius in Fahrenheit" << endl;
cout << "2 - Meter in Fuss" << endl;
cout << "3 - Euro in US Dollar " << endl;
cin >> auswahl;
double feet_conv = 3.28084;
double dollar_conv = 1.11;
ergebnis = (auswahl == 1) * ((eingabe * 9.0 / 5) + 32) +
(auswahl == 2) * eingabe * feet_conv +
(auswahl == 3) * eingabe * dollar_conv;
cout << "Ihr Ergebnis ist: " << ergebnis << endl;
return 0;
}
Can do without if/switch or ternary operator, or comparison, just boolean operations, implicit bool-to-integer conversion, and multiplication:
#include <iostream>
using namespace std;
double c_zu_f(double in) { return in * (9.0/5.0) + 32.0; }
double m_zu_ft(double in) { return 3.0 * in; } // approx.
double eur_zu_usd(double in) { return 1.2 * in; } // approx.
int main()
{
double eingabe;
int auswahl = 0;
double ergebnis;
//zahleneingabe
cout << "Ihre Eingabe: ? " << endl;
cin >> eingabe;
cout << "Ihre Eingabe: " << eingabe << endl;
system("PAUSE");
//abfragenausgabe der umrechnungsart
cout << "Ihre Auswahl der Umwandlung: " << endl;
cout << "1 - Celsius in Fahrenheit" << endl;
cout << "2 - Meter in Fuss" << endl;
cout << "3 - Euro in US Dollar " << endl;
cin >> auswahl;
bool auswahl_gueltig = auswahl && (auswahl & 0x03); // oder nur (auswahl & 0x03), da 0 --> false
bool auswahl_ist_eins = auswahl_gueltig && ( (auswahl & 1) && !(auswahl & 2));
bool auswahl_ist_zwei = auswahl_gueltig && (!(auswahl & 1) && (auswahl & 2));
bool auswahl_ist_drei = auswahl_gueltig && !( auswahl_ist_eins || auswahl_ist_zwei );
ergebnis = auswahl_ist_eins * c_zu_f(eingabe) + auswahl_ist_zwei * m_zu_ft(eingabe) + auswahl_ist_drei * eur_zu_usd(eingabe);
cout << "Ihr Ergebnis ist: " << ergebnis << endl;
system("PAUSE");
}
If given invalid (not 1, 2, or 3) auswahl, the result shown will be zero, but that's as good as you can get without if or ternary operator (though you could assert(auswahl_gueltig) of course, which isn't exactly the same but at least won't fail silently).
Can make the implicit bool to int conversion explicit with a cast, too, if you like -- but that's unnecessary and ugly.
Give an integer named choice representing the user's choice, the following expression evaluates to 0 when the the user chooses 1 or 2 and it evaluates to 1 when the user chooses 3:
(choice - 1) * (choice - 2) * 0.5
Therefore, this expression is a pretty good replacement for choice == 3, which you are not allowed to use in this homework problem because it contains ==.
With the hint above, you can probably guess what to do. But here is a complete solution:
#include <iostream>
int main()
{
double input;
std::cout << "Enter your input: " << std::endl;
std::cin >> input;
int choice;
std::cout << "Choose your conversion: " << std::endl;
std::cout << "1: Celsius to Fahrenheit" << std::endl;
std::cout << "2: Meters to feet" << std::endl;
std::cout << "3: Euros to US Dollars" << std::endl;
std::cin >> choice;
double result =
(choice - 2) * (choice - 3) * 0.5 * (1.8 * input + 32) + // C to F
(choice - 1) * (choice - 3) * -1 * (3.28084 * input) + // m to ft
(choice - 1) * (choice - 2) * 0.5 * (0.97 * input) // Euro to USD
;
std::cout << "Result: " << result << std::endl;
}

Recurrence in Math exercise

I am still trying to learn algorithms, I have a homework. I must make an output
Sum of : 1/2 + 1/4 + 1/6 - 1/8 + 1/10 + 1/12
Result : 0.975
But output of my program
Sum of : 1/2 + 1/4 + 1/6-1/8 + 1/10 + 1/12
Result : 0.975
I dont know how to make space negative sign, if i use cout there will show twice negative sign.
my program
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int i ,sign, p, q, n;
double x , S;
S=0;
cout << "Sum of :";
for (i=1; i <= 6; i++)
{
if ( (i % 4 == 0) && ( i > 1 ) ) // to make condition where the number become negative
{
sign = -1;
}
if ( ( i % 4 != 0 ) && ( i > 1 ) ) // to make condition where the number become positive
{
sign = 1;
cout << " + ";
}
if ( i == 1 ) // to prevent 1st number not show " + " symbol
{
sign =1;
}
p = sign*1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
}
cout << "\n" << S;
}
I realise that my program has too many operations which may be avoided, could u help me make it more effecient ?
So your
cout << p << "/" << q;
will always have that format if p is negative.
Instead (This workaround is intended to be simple)
if(p < 0) {
cout << " - " << p*-1 << "/" << q;
} else {
cout << p << "/" << q;
}
That should do it.
If you are looking to use recursion as you have indicated in the subject, then here is what you can also refer.
static void recurse(int i, int limit){
int sign = 0, p, q, n;
double x, S;
S =0;
if (i == 1) // to prevent 1st number not show " + " symbol
{
sign = 1;
cout << "Sum of : ";
}
else if (i< 1 || i> limit){
return ;
}
else {
sign = (i % 4 == 0) ? -1 : 1;
if (sign > 0){
cout << " + ";
}
else {
cout << " - ";
}
}
p = 1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
recurse(i+1, limit);
}
Call using:
int main ()
{
recurse(1, 6);
cout << "\n";
}

Formatting the output of a C++ program

I have already written most of the code for the problem and it works. I'm just unsure of how to format the output.
Problem : Design and develop a C++ program for Calculating e(n) when delta <= 0.000001
e(n-1) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n-1)!
e(n) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n)!
delta = e(n) – e(n-1)
You do not have any input to the program. Your output should be something like this:
N = 2 e(1) = 2 e(2) = 2.5 delta = 0.5
N = 3 e(2) = 2.5 e(3) = 2.565 delta = 0.065
#include <iostream>
using namespace std;
//3! = 3 * 2!
//2! = 2 * 1!
//1! = 1
int factorial(int number)
{
//if number is <= 1, return 1
if (number <= 1)
{
return 1;
}
// otherwise multiply number by factorial(number - 1)
else
{
//otherwise multiply number by factorial(number - 1) and return it
int temp = number * factorial(number - 1);
cout << "factorial of " << number << " = " << temp << endl;
return temp;
}
}
double sumOfFactorials(int n)
{
double sum = 0;
//loop from 1..n, adding the factorial division to a sum
for (int i = 1; i <= n; i++)
{
double dividedValue = 1.00000 / factorial(i);
cout << fixed;
sum = sum + dividedValue;
}
return sum;
}
/**
* Compute the sum of 1 + ... + 1/(n!)
* input number: 1
* output number: 1 + ... + 1/(input!)
*/
double e(int n)
{
double value = 1 + sumOfFactorials(n);
return value;
}
int main()
{
cout << "e:" << e(3) << endl; // 1 + sumOfFactorials(3)
cout << "sumOfFactorials: " << sumOfFactorials(3) << endl; //0 + 1/1! + 1/2! + 1/3!
}
You have the right code, All you need is to format the output. Just modify the main() method. here is a snippet you can try.
NOTE : There is an error in the precision of the answer, I think you can correct it.
PS : Please uncomment your debugging cout lines.
int main()
{
for(int i = 2; i<4; i++){
double en_1 = e(i-1);
double en = e(i);
double delta = en - en_1;
cout << "N = "<<i;
cout << " e("<< (i-1) <<") = " << en_1;
cout << " e("<< (i) <<") = " << en;
cout << "delta = " << delta;
cout << "\n";
}
}