0
C++ homework: puzzle
Martha thought about two integers: a and b (a>=b). You know their sum and the subtraction. Can you tell what numbers she thought of ? INPUT Two natural numbers: a+ b and a-b (0<=a-b<=a+b<=1000000000) OUTPUT Two numbers after a space: a and b EXAMPLE for the input data/numbers 4 2 The correct answer is 3 1 And my code is: #include <iostream> using namespace std; int main() { int a, b, c, d; cin>>c; cin>>d; ((a>=b)); c= (a+b); d= (a-b); if ((a-b>=0) & ((a-b) >= (a+b)) & (a+b <= 1000000000)) cout<<a<<" "<<b; return 0; } And my code is totally wrong... I don' know how to do it correct.... Can someone help?:)
8 Réponses
+ 2
The four program lines that lie between cin>>d; and cout<<a<<" "<<b; need to be replaced. To do that, you need a better understanding of how programming works.
Here are a couple tips that might help. Programming in C++ is not quite like doing algebra. The language does not automatically balance both sides of the equals sign to solve a solution for you. Instead, think of a formula, where the right side of the equals sign is the calculation, and the left side is where you store the result. In order to calculate a and b, the statements should look more like this:
a = (c + d)/2;
b = (c - d)/2;
Now a and b are calculated, and you can print the results that are stored in them. There is no need for the 'if' statement here. Replace those four lines with the two lines I gave, and then it should work correctly.
0
c = a + b = 4
d = a - b = 2
=>c+d = 4+2 = 6 ( => I.e a+b+a-b = 2a =6 =>) so a = 6/2=3
=>c = a+b = 3+b=4 => b= 4-3=1.
Implement this to code.
0
your question is not clear at all.
may be if you can tell the process that gone on between the input and output then it can be good else the problem can not be solved through programming.
0
My question is like my homework is;)
0
Brian IT IS WORKING !!! thank you so much :D
if my input will be:
5
3
and output is 4 1
which is correct
but if my input will be
5
2
output is: 3 1
which means 3+1= 4 not 5
so the program is working but not all is correct ?
maybe the content of the task from my teacher is too less specific ?
0
Martyna T there are no integers that both add and subtract to get 5 and 2. The solution would be only real numbers a=3.5 and b=1.5. Using 5 and 2 is invalid input.
Appropriately, the program is using integer data types. When you divide in integer math, you get only integer results. If there is a decimal portion, then the result gets truncated down to only the integer. Hence, 5 and 2 gives the results of a=3 and b=1.
Have you heard of the GIGO principle with computers? GIGO means Garbage In => Garbage Out!
0
Martyna T I mean Simply do like this :
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin>>a;
cin>>b;
cout<< (a+b)/2 << " "<<a - (a+b)/2;
return 0;
}
0
Thank You all :)