Addition and Subtraction giving incorrect results - c++

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.

Related

Is there a way to hide variables in cout (C++)?

I'm having an issue figuring out how to hide a specific variable (if that is even possible) in a cout function. Basically I need to do a number guess game, which would be easy enough except our teacher wants us to do it like a random math equation. Which... would honestly still be fairly easy except the way we have to do it is the program has to randomly create the problem and then randomly pick one of the 3 numbers to display and the user has to guess the other two missing numbers. For example if the program picked 20 + 32 = 52 it could potentially display __ + 32 = __.
I've gotten that far however I can't figure out how to make it so it displays like that but still allows me to put the line something like this
cout << num1 //Hidden << " + " << num2 << " = " << num3 //Hidden
However like I said I don't even know if that is possible if not then I will probably have to rewrite the whole program. This is what I have so far:
int main()
{
int num1, num2, num3, random1, guess1, guess2;
string play = "";
cout << "Would you like to run the number guessing program? (enter yes or no): ";
getline(cin, play);
for (int i = 0; i < play.length(); i++)
{
play[i] = tolower(play[i]);
}
//Random seed
srand(time(0));
while (play == "yes")
{
//Generate random numbers and num3
num1 = 1 + rand() % 50 + 1;
num2 = 1 + rand() % 50 + 1;
num3 = num1 + num2;
int pickRandom[3] = { num1, num2, num3 };
//Display random elements
random1 = pickRandom[rand() % 3];
if (random1 == num1){
cout << "\nYour randomly generated number problem: " << num1 << " + " << "__" << " = " << "__" << endl;
}
if (random1 == num2){
cout << "\nYour randomly generated number problem: " << "__" << " + " << num2 << " = " << "__" << endl;
}
if (random1 == num3){
cout << "\nYour randomly generated number problem: " << "__" << " + " << "__" << " = " << num3 << endl;
}
//Get Guesses
cout << "\nBased off of this information please make an educated guess as to what the two missing numbers are.";
cout << "\n\nGuess for number 1 (between 1 and 100): ";
cin >> guess1;
while ((guess1 > 100) || (guess1 < 0))
{
cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
cout << "\nGuess for number 1 (between 1 and 100): ";
cin >> guess1;
}
cout << "\n\nGuess for number 2 (between 1 and 100): ";
cin >> guess2;
while ((guess2 > 100) || (guess2 < 0))
{
cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
cout << "\nGuess for number 2 (between 1 and 100: ";
cin >> guess2;
}
if (guess1 == )
}
return 0;
}
I don't think you can hide variables in cout. But you can use a variable instead of hardcoding "__".
For instance, you can simply write this:
if(guessed_var1_correctly)
var1 = num1
else
var1 = "__"
if(guessed_var2_correctly)
var2 = num2
else
var2 = "__"
if(guessed_var3_correctly)
var3 = num3
else
var3 = "__"
cout << "\nYour randomly generated number problem: " << var1 << " + " << var2 << " = " << var3" << endl;
where var1, var2, var3 are output variables. If the player guesses it correctly, it'll display the actual value num1, num2, or num3. If not, it'll simply display "__".

representing negative outputs dynamically in Taylor series expansion --> C++

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.

Exits while loop before condition is false?

This is a pretty specific question but my program seems to exiting its while loop before the condition is false. I added in quite a few memory checks for safety when I was debugging and it prints to screen that counter is 4 and SqRoot is 6 at the end which means it should still be looping through (TestNum=32). I definitely know it's getting past the loop with counter<=SqRoot because it prints both "The integer 32 is composite" and "The integer 32 is prime". Any help is very appreciated! Thanks so much
EDIT: I changed the overall logic of program and it is working now. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
//Declare variables.
int TestNum, DivInt, SqRoot, PrintCounter(0), oppcounter;
float DivFloat, counter(2);
int main()
{
//Prompt user for input.
cout << "Input an positive integer to test its primality.";
cin >> TestNum;
//Check if input is positive.
while (TestNum < 0)
{
cout << "Please input a *positive* integer.";
cin >> TestNum;
}
//Square root.
SqRoot = sqrt(TestNum)+1;
//Loop to test if prime.
while (counter<=SqRoot)
{
++counter;
DivFloat = TestNum/counter;
DivInt = TestNum/counter;
oppcounter = TestNum/counter;
if (DivFloat-DivInt == 0)
{
++PrintCounter;
if (PrintCounter==1)
{
cout << "The integer " << TestNum << " is composite.\n " \
<< TestNum << " is divisible by\n";
};
cout << counter << " " << oppcounter;
cout << "counter* " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
}
}
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
cout << "counter " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
//End main.
return (0);
}
I am seeing the opposite behavior of what you are describing, and I can see why. It's possible that the code you have posted is different than the code you are executing.
As an aside, I added the line
cout << endl;
after the line
cout << " DivFloat " << DivFloat;
at couple of places to make the output more readable.
When I enter 32, I see the following output:
The integer 32 is composite.
32 is divisible by
4 8
counter* 4 TestNum 32 DivInt 8 SqRoot 6 DivFloat 8
counter 7 TestNum 32 DivInt 4 SqRoot 6 DivFloat 4.57143
When I enter 17, I see the following output:
counter 6 TestNum 17 DivInt 2 SqRoot 5 DivFloat 2.83333
The reasons for that:
You don't break out of the while loop when you have detected that a number is a composite.
As a result of that, you always break out of the while loop only when counter<=SqRoot evaluates to false. As a result, in the code below,
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
you never execute the line in the if block.
The program should behave correctly if you break out of the while loop when you detect a composite and change the logic in the last if block to:
if (counter > SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
Why so strange check for prime?
for(int i = 2; i*i <= n; ++i)
{
if (n % i == 0)
{
cout << "not prime";
break;
}
}

error expected unqualifed-id before '{' token [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include <iostream>
using namespace std;
int num1, num2, num3, num4, num5, result, result1, result2, result3, value, cont;
//number user enters/variable
int main()
{
cout << "please enter the operation,+ for addtion,- for subtaction,* for multiplatcion,/ for division"
;cin >> value
;cout << "please enter the first number number:";
cin >> num1
;cout << "please enter the second number: ";
cin >> num2
;if(value == '+' )
;result = num1 + num2;
cout << num1 << " plus " << num2 << " is equal to: " << result << ".\n";
if(value = '-' )
;result = num1 - num2;
cout << num1 << " minus " << num2 << " is equal to: " << result << ".\n";
if(value = '*' )
;result = num1 * num2;
cout << num1 << " times " << num2 << " is equal to: " << result << ".\n";
if(value = '/' )
;result = num1 / num2;
cout << num1 << " divided by " << num2 << " is equal to: " << result << ".\n";
}
{
cout << "press 1 to enter more numbers, or press 0 to not"
cin >> cont
if(cont = 1)
cout << "please enter the operation,+ for addtion,- for subtaction,* for multiplatcion,/ for division"
cin >> value1
cout << "please enter the next number:";
cin num3
else(cont = 0)
else(value1 = +)
;result1 = result + num3;
cout << result << " plus " << num3 << " is equal to: " << result1 << ".\n";
else(value1 = -)
;result1 = result - num3
cout << result << " minus " << num3 << " is equal to: " << result1 << ".\n";
else(value1 = *)
;result1 = result * num3
cout << result << " times " << num3 << " is equal to: " << result1 << ".\n";
else(value1 = /)
;result1 = result / num3
cout << result << " divided by " << num3 << " is equal to: " << result1 << ".\n";
}
{
cout << "press 1 to enter more numbers, or press 0 to not"
cin >> cont
if(cont = 1)
cout << "please enter the operation,+ for addtion,- for subtaction,* for multiplatcion,/ for division"
cin >> value1
;cout << "please enter the next number: ";
cin >> num4
else(cont = 0)
else(value2 = +)
;result2 = result1 + num4;
cout << result1 << " plus " << num4 << " is equal to: " << result2 << ".\n";
else(value2 = -)
;result2 = result1 + num4;
cout << result << " minus " << num3 << " is equal to: " << result1 << ".\n";
else(value2 = *)
;result2 = result1 * num4
cout << result << " times " << num3 << " is equal to: " << result1 << ".\n";
else(value2 = /)
;result2 = result1 / num4
cout << result << " divided by " << num3 << " is equal to: " << result1 << ".\n";
{
cout << "press 1 to enter more numbers, or press 0 to not"
cin >> cont
if(cont = 1)
cout << "enter the operation,+ for addtion,- for subtaction,* for multiplatcion,/ for division"
cin >> value2
;cout << "please enter the next number: ";
cin >> num5
if(value3 = +)
;result3 = result2 + num5;
cout << result2 << " plus " << num5 << " is equal to: " << result3 << ".\n";
else(value3 = -)
;result3 = result2 - num5
cout << result << " minus " << num3 << " is equal to: " << result1 << ".\n";
else(value3 = *)
;result3 = result2 * num5
cout << result << " times " << num3 << " is equal to: " << result1 << ".\n";
else(value3 = /)
;result3 = result2 / num5
return 0;
the error happens at line 34, where it says {
so please help me!
the code is for a basic calculator
feel free to use it if you can correct line 34!
I have no idea what is causeing it
I am a noob to the c++
codeing so please help!
I have done my own research and I cannot find it.
You can't say stuff like
else(value1 = +)
in C++. You must mean something else, but it is hard to guess what because there are so many errors in your code. In general, you cannot just type random characters and expect a functioning program.
The error stems from the additional { ... } blocks following the main function, since the compiler does not know what to do with code outside of declarations . But that is not the only problem with your code:
Putting a semicolon directly after an if statement means "if the condition is true do nothing anyway", and the next statement is executed either way.
if(value = +) should be if(value == '+') etc - you mixed the association = with comparison ==, plus you try using an operator + instead of a character '+'* what is else(something) supposed to do? Code blocks are put in {}s, not ()s
May I suggest you start programming in an easier language like Python? Its meaningful indentation and the lack of semicolons makes life a lot easier...
Get rid of all of the
}
{
and you'll be able to proceed to fixing your next error.
When you write braces like the following: }
you're closing your block of code, which in this case is your main function.
and when you write the following: {
The compiler thinks that you're trying to start a new function, but there's not function signature and you get an error.
It looks to me like you intend all of this code to be inside of your main function, so you want something like the following:
int main()
{
//insert all of your code here
return 0;
}

Truncate C++ string fields generated by ostringstream, iomanip:setw

In C++ I need string representations of integers with leading zeroes, where the representation has 8 digits and no more than 8 digits, truncating digits on the right side if necessary. I thought I could do this using just ostringstream and iomanip.setw(), like this:
int num_1 = 3000;
ostringstream out_target;
out_target << setw(8) << setfill('0') << num_1;
cout << "field: " << out_target.str() << " vs input: " << num_1 << endl;
The output here is:
field: 00003000 vs input: 3000
Very nice! However if I try a bigger number, setw lets the output grow beyond 8 characters:
int num_2 = 2000000000;
ostringstream out_target;
out_target << setw(8) << setfill('0') << num_2;
cout << "field: " << out_target.str() << " vs input: " << num_2 << endl;
out_target.str("");
output:
field: 2000000000 vs input: 2000000000
The desired output is "20000000". There's nothing stopping me from using a second operation to take only the first 8 characters, but is field truncation truly missing from iomanip? Would the Boost formatting do what I need in one step?
I can't think of any way to truncate a numeric field like that. Perhaps it has not been implemented because it would change the value.
ostream::write() allows you to truncate a string buffer simply enough, as in this example...
int num_2 = 2000000000;
ostringstream out_target;
out_target << setw(8) << setfill('0') << num_2;
cout << "field: ";
cout.write(out_target.str().c_str(), 8);
cout << " vs input: " << num_2 << endl;
If you assume that snprintf() will write as many chars at it can (I don't think this is guaranteed),
char buf[9];
snprintf(buf, 10, "%08d", num);
buf[8] = 0;
cout << std::string(buf) << endl;
I am not sure why you want 2 billion to be the same as 20 million. It may make more sense to signal an error on truncation, like this:
if (snprintf(buf, 10, "%08d", num) > 8) {
throw std::exception("oops")
}