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.
Related
I am trying to produce code with an output of:
Enter six fp numbers on a single line, separated by spaces: 1.5 2.1 3.8 4.2 5.7 6.1ENTER
Sum of 1.5 + 2.1 + 3.8 + 4.2 + 5.7 + 6.1 = 23.4\n
Average = 3.9\n
I started C++ a day ago so I literally don't know what I'm doing. This is the script I currently have. I know there are some punctuation errors.
#include <iostream>
using namespace std;
int main ()
{
int num1;
int num2;
int num3;
int num4;
int num6;
cout << "Enter six fp numbers on a single line, separated by spaces: ";
cin >> num1 >> num2 >> num3 >> num4 >> num5 >> num6 << endl;
How do I avoid issues listing numerical values and how do I insert a sum and average function? Any help would be appreciated thank you.
I'll give you this much as a way to get started. This just computes the sum on the fly, rather than storing it in a vector, which is another great way t do this.
#include <iostream>
int main ()
{
std::cout << "Enter six fp numbers on a single line, separated by spaces: ";
double sum = 0.0;
double f;
for( int i = 0; i < 6; i++ )
{
std::cin >> f;
sum += f;
}
std::cout << "Sum is " << sum << "\n";
std::cout << "Average is " << (sum/6) << "\n";
}
Output:
Enter six fp numbers on a single line, separated by spaces: 1.2 3.4 5.6 7.8 9.1 2.3
Sum is 29.4
Average is 4.9
What you did was just declare 5 integer variables, stored the numbers in them and simply calculated average there are some issues with that
1. The numbers you have stored are of the type float
2. There are simply better ways to do it but since you started with
C++ recently it is understandable
If you are not familiar with loops I suggest you read up on them but since we know the no of variables, a for loop would work fantastically here.
So what we can do is
#include <iostream>
int main ()
{
std::cout << "Enter six numbers on a single line, separated by spaces: ";
double sum = 0.0,buffer;
for( int i = 0; i < 6; i++ ) //For 6 iteration 0-5
{
std::cin >> biffer;
sum = sum + buffer;
}
std::cout << "The sum of the Given nos is:- " << sum << "\n";
std::cout << "Average of the given nos is:- " << (sum/6) << "\n";
}
Output:
Enter six fp numbers on a single line, separated by spaces: 1.2 3.4 5.6 7.8
9.1 2.3
Sum of the Given nos is:- 29.4
Average of the given nos is:- 4.9
You can replace 6 with any number to make this program scalable
Good Luck
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.
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.
I added comments to the code, do I have a compiler issues? I can't figure it out, I tried looking on google and the book but I cant figure out why the first half of code only accepts the input with space between the number and unit and second code accepts the number and unit together.
I'm using code blocks. So far I tried closing it and opening it again.
int main(){
constexpr double dollar_to_euro = 0.91;
constexpr double dollar_to_yen = 117.07;
constexpr double dollar_to_pounds = 0.70;
double sum = 1;
char curr = '\0'; // tried replacing '\0' with '0' and ' '
cout << "Please enter sum, followed by currency for conversion.\n"
<< "U for dollar, E for euro, Y for yen and P for pounds.\n";
cin >> sum >> curr; // This is my issue, it does not want to accept "sumcurr" together, it only accepts it if theres space in between
// yet on the second code for inches or centimeters it does accept them being together. Look down.
// For example entering "5 E" works, yet "5E" does not work.
if(curr=='E')
cout << "The amount " << sum << " euro is " << sum/dollar_to_euro << " dollars\n";
else
cout << "GOD DAMMIT !!!!\n";
constexpr double cm_per_inch = 2.54;
double len = 1;
char unit = '\0';
cout << "Please enter length followed by unit.\n";
cin >> len >> unit; // Over here it works, this is an example from a book. Entering "5i" works.
if(unit=='i')
cout << len << " in == " << cm_per_inch*len << "cm.\n";
else
cout << "Wrong input !\n";
}
The problem here is that E/e is valid in a floating point number but 5E/5e is not a valid floating point number as you need a value after the E/e. So when you enter 5e the input for sum fails because of the invalid syntax where 5e0 would work. If you use anything other than E/e then it will work like your second example.
For more information on the format of floating point numbers see: Cppreference floating point literal