I am just starting to learn C++ in college and our first assignment is to make a program that will do basic math. i feel like my code is not mistaken, but when i display the variable "sum", i get an answer that is way off. the value for the answer changes even if i input the same number multiple times. for example, i entered 2 for each variable and i got 1864273973 the first time and 1772335157 the second time. what could be causing this? i am using a macbook pro and code blocks, if anyone is wondering. i have also included my code.
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
//variabe declarations
int number, number2;
int sum, difference, product, dividend;
//calculations
sum = number + number2;
difference = number - number2;
product = number * number2;
dividend = number/number2;
//user inputs
cout << "\n1 of 2: Enter a number: ";
cin >> number;
cout << "\n2 of 2: Enter second number :";
cin >> number2;
cout << "\nNumber 1 entered: " << number << "\nNumber 2 entered: " << number2;
//output
cout << "\n" << number << "+" << number2 << "=" << sum << "\n";
}
C++ and almost every language nowadays use a structured system. It reads from top to bottom, so if you say "a = b+c" and then cin >> a, the calculation from b+c will be lost after the new input.
You are trying to calculate using variables that are declared but not initialized. In c++, this will cause the new variable to just receive "trash", a number you probably don't want. To correct this, I think you want to actually receive number and number2 BEFORE doing the math.
Related
I've made a simple c++ program that takes in two numbers, clears the screen, and then outputs the sum of those two numbers to the terminal window. It works great. Typing 5 as the first number and 10 as the second outputs 15.
Except there's one issue. When running the program with the first number being 5 and the second being something very long, such as:
3285720358162039587169230839461283795732948567123857690,
the program doesn't output the right number, and doesn't show the correct number that the user typed either.
For example, when using the previous two numbers, the "sum" will be: -2147483644, when it should be the long number with a 5 instead of a zero on the end.
Here's my code:
#include <iostream>
int main() {
system ("clear");
int num1 = 0;
int num2 = 0;
std::cout << "What is the first number?: ";
std::cin >> num1;
std::cout << "What is the second number?: ";
std::cin >> num2;
system ("clear");
std::cout << "The sum of " << num1 << " and " << num2 << " is: " << (num1 + num2) << "\n";
}
There are limits on integer size. ~~You're probably going to declare the numbers as a long long.~~
EDIT: Ted is correct, long longs won't be large enough for that particular input either.
In order to help us understand type casting in C++, we are required to perform addition of two int's as shown below. If we provide two int's as 4 and 5 respectively, the output should be 4 + 5 = 9.
I tried to follow this type casting tutorial without any success. Could someone please provide me a hint or something?
Quoting the assignment verbatim.
Your friend wrote a program called an adder. The adder is supposed to take two numbers inputted by a user and then find the sum of those numbers, but it’s behaving oddly.
Your first task is to figure out what is wrong with the adder. Your second task is to fix it.
Hint(s) to identify the problem
Try entering 1 and 1. You expect the output to be 2 but you get 11 instead. Similarly, if you enter 3 and 4, you expect the output to be 7 but you get 34. Remember, string concatenation also uses the + operator.
Hint(s) to identify the solution
The + operator functions differently based on the type of data that comes before and after it. What data types will cause the + operator to calculate a mathematical sum? What data type is present in the program now? How do you convert from one data type to another? Check out the Type Casting page for some idea
#include <iostream>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
string sum = num1 + num2;
cout << ( num1 + " + " + num2 + " = " + sum ) << endl;
return 0;
}
The problem with the code is that it is performing string concatenation when it needs to perform arithmetic addition instead. So you need to get the user's input into numeric variables, not strings. The assignment even alludes to this.
However:
Check out the Type Casting page for some idea
That is bad advice for this task, as you can't solve the problem with type casting.
You need to either:
Change the code to use int variables instead of string variables. This is the preferred solution, eg:
#include <iostream>
using namespace std;
int main() {
int num1;
int num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = num1 + num2;
cout << num1 << " + " << num2 << " = " << sum << endl;
return 0;
}
Otherwise, if you want to continue using string variables, you need to convert (not type cast!) their values into int values at runtime, and then convert back afterwards, eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = stoi(num1) + stoi(num2);
cout << ( num1 + " + " + num2 + " = " + to_string(sum) ) << endl;
return 0;
}
if you typecast a character or string it get's converted into its equivalent ASCII value , either you need to use stoi or subtract from '0' for every digit position(a bit repeatitive work) go with stoi
The problem is that my program does not give accurate average for numbers with more than 9 digits.
Can somebody point out what am I doing wrong and how do I fix that? Is there anything I can do to improve the code any further?
The code is
#include <iostream>
using namespace std;
int main(){
cout << " Average Finder \n"; //So that the title is displayed properly.
int NUM1,NUM2,AVG; /*I am defining the variables as integers, seemed like the best option.
Should I use long float? Does that even work?*/
cout << "Type the First Number: "; // for the display
cin >> NUM1; // the program asks for the first user input and stores it in integer variable NUM1
cout << " \n";
cout << "Type the Second Number: ";
cin >> NUM2; // the program asks for the second user input and stores it in integer variable NUM2
cout << " \n";
AVG = ((NUM1+NUM2)/2); //this line calculates their average
cout << "The Average of given numbers is = ";
cout << AVG;
return 0;
}
Here is the command line executions.
PS D:\Workspace\Coding\C++> .\ALG001.EXE
Average Finder
Type the First Number: 1111111111
Type the Second Number: 1111111111
The Average of given numbers is = -1036372537
Your NUM1 and NUM2 are of type int. int variables have a maximum value, on most systems it is 2147483647.
When NUM1 = 1111111111 and NUM2 = 1111111111, then NUM1 + NUM2 will be bigger than the the maximum value 2147483647. This is called overflow.
Technically in c++ this is undefined behaviour, but on most systems it will wrap around giving you negative values and explaining your output.
If you want your variables to store larger values, use long or even long long.
You'll want to use floating point for the average. And beware of integer division:
double average = 0.0;
average = (1 + 2 + 3) / 3.0;
std::cout << average << "\n";
With integer division, 1 / 3 == 0.
Sorry for the simple question, but I couldn't find an already available answer elsewhere.
I am building a fractional calculator that can either add, subtract, divide, or multiply two fractions(e.g 4/3 + 5/2). Firstly however, I need to parse out different elements of the user's input, like the arithmetic operator, and the numerator and denominators of the two fractions and store those elements in order to manipulate them down the line.
I thought of using a series of getline(string) while altering the default delimiter to discard whitespace and / signs. However, when I try to execute my program, there seems to be issues with getline(string).
Might somebody be able to point out my surely amateur mistake? The compiler isn't throwing any errors, so I'm a bit lost on what it might be.
EDIT: I'VE SINCE BEEN ABLE TO RESOLVE THE ISSUE THANKS TO HELP. THANK YOU EVERYONE
#include <string>
#include <iostream>
using namespace std;
int main()
{
string numeratorfirst;
string denominatorfirst;
string arithoperator;
string numeratorsecond;
string denominatorsecond;
cout << "Enter the two fractions and the operator you want to use(IE: 3/4 + 4/6): ";
getline(cin, numeratorfirst, '/');
getline(cin, denominatorfirst, ' ');
getline(cin, arithoperator);
getline(cin, numeratorsecond, '/');
getline(cin, denominatorsecond, ' ');
cout << " " << endl;
cout << "Your fraction is: " << numeratorfirst << "/" << denominatorfirst << " " << arithoperator << " " << numeratorsecond << "/" << denominatorsecond << endl;
system("pause");
return 0;
}
It might be easier using scanf():
int numeratorfirst;
int denominatorfirst;
char arithoperator;
int numeratorsecond;
int denominatorsecond;
cout << "Enter the two fractions and the operator you want to use(IE: 3/4 + 4/6): ";
int tokens = scanf("%d/%d %c %d/%d", &numeratorfirst, &denominatorfirst,
&arithoperator, &numeratorsecond, &denominatorsecond);
if (tokens != 5)
return 1;
This works, and it rejects invalid inputs like "foo/bar + baz/qux".
If you want a "more C++ like" solution, try this:
int numeratorfirst, denominatorfirst, numeratorsecond, denominatorsecond;
char slashfirst, slashsecond;
char arithoperator;
cout << "Enter the two fractions and the operator you want to use(IE: 3/4 + 4/6): ";
cin >> numeratorfirst >> slashfirst >> denominatorfirst >> arithoperator
>> numeratorsecond >> slashsecond >> denominatorsecond;
if (!cin || slashfirst != '/' || slashsecond != '/')
return 1;
My program is meant to ask a user to input an equation. Then find the maximum over an interval given by the user. When I compile my program, the output I get is:
Please complete the equation to be evaluated f(x)=
Please enter the first number of the interval to be checked:
Please enter the last number of the interval to be checked:
Please enter the desired initial step size:
sh: PAUSE: command not found
with the last line repeating many times.
I think the problem here has something to do with having the user input the equation to be tested. However, I'm unsure of how to fix this.
Here's my code
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, delta, fx, x, y;
int max = 0;
cout <<"Please complete the equation to be evaluated f(x)= " << endl;
cin >> fx;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = fx;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<"to " << b <<"is " << delta;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{
system ("PAUSE");
}
}
return 0;
}
F(x) shouldn't be an integer variable, it should be a string variable. That way, the user can enter operators as characters instead of the compiler thinking they should be numbers. You would then have to process the string to determine the equation; this would require some thought, and possibly a more advanced data structure such as a binary tree.
Simply don't use system("pause"); in the if statement and you'll lose that error:
"sh: PAUSE: command not found". Place it right before the end of the main.
system("pause");
return 0;
As pointed out by others, the form of f(x) could be an issue with the above code.
Consider to redesign what to achieve for your program. One possibility is to narrow down the f(x) as polynomial function so that you can avoid parsing general algebraic equation, in this case you can ask:
how many degree of the polynomial ? upon this, it is followed by input the coefficient value for each factor in the polynomial equation.
This way, you can still use integer (or double - better) in the program.