I am stuck trying to figure out a way using C++ to solve a situation where the user inputs a value using cin and then have the computer solve for a way to get the value of cin, given that the format is given. a super fast example is written below.. yes i know there is a lot of code missing... but the concept is there..
int x;
int y;
int w;
int x = 30 < w < 50;
int y = 60 < w < 90;
cin >> input;
x + y = input;
cout << x;
cout << y;
Naturally though x + y cant be on the lvalue on the right. so i cant just write x + y = input.. so how would i have it solve x + y = input? Additionally I want x and y to be between the numbers listed, which limits the numbers between those inputs.. however in my actual coding i did this with a function.
has school even started yet? no its not homework. im teaching myself C++.. – Sean Holt 1 min ago edit
No im just trying to figure a way of having the computer solve for x/y of an input value if x and y are between specified values in a function
It looks like you think that C++ is going to solve equations for you. It won't. C++ is an imperative style language that is based around the concept of you telling it exactly what to do.
You will have to figure out how to solve for x and y so that you can make an algorithm. This algorithm is then what you make your program from.
There exists other languages in which you can in a sense describe what you want and have the compiler or runtime figure out how to get it for you. C++ is not one of them.
Different ways to solve your particular problem would be to set up an equation system and solving that. Or do brute force approach and iterate through the values of x and y in order to find out which values match.
It looks like you have a 'mathematical' problem here: a couple of values constrained by equations, and you want 'the computer' to find all possible values that fit into the constraints (equations). Am I right?
While some computer programs can certainly do that, the C++ language is not designed for this purpose. The role of the C++ is to give you a way of giving instructions to the processor, like "store this value in memory" or "add these two numbers". But there is no way of saying "solve this mathematical problem".
What you need is some equation solver. But I am not familiar with any. There are tools like Matlab or Mathematica. But I do not think they are free.
If you want to solve the math problem algorithmically, here is a brute force idea in pseudocode:
Input a number.
for each value x between 30 and 50
for each value y between 60 and 90
if x+y equals the number
print x and y
Now you can take a good book or tutorial and code in C++. Look for the for and if keywords (algorithmic concepts of iteration and selection) in your teaching material. Have fun!
This case can be solved trivially by interval arithmetic. C++ code that solves your "sum of two interval-constrained variables problem" is given below.
int min_x = 30, max_x = 50;
int min_y = 60, max_y = 90;
// solutions exist in this interval
int min_z = min_x + min_y, max_z = max_x + max_y;
cin >> input;
// solutions possible?
if (input >= min_z && input <= max_z)
{
// determine solution interval for x (y is dependent)
cout
<< "Solution:\n"
<< "x in [" << min(max( input - max_y , min_x),max_x)
<< ";" << min(max( input - min_y , min_x),max_x) << "], "
<< "y = " << input << " - x" << endl;
}
else
{
cout << "No solution." << endl;
}
Computers are "basically stupid" and if they do smart things it is the software.
Using a general purpose programming language like C++ requires you (or at least
the libraries you eventually use) to be very specific on how exactly to solve
a problem based on the simple arithmetic means of the bare computer.
Although the programming language won't magically and somehow do things
for you, algorithms exist to solve many mathematical standard problems such
as e.g. systems of equations. Numerical Recipes in C++ covers a variety of
algorithms and their C++ implementations.
Related
OK, to start off I am a complete beginner in a computer science class. I could ask my teacher, but I don't have time to do so. So, expect some really dumb errors that I can't see and I am using eclipse.
here's my code:
#include <iostream>
using namespace std;
int something()
{
int big = 1000;//largest number is 1000
int small = 1;//smallest number is 1
//so, best guess is to go in the middle
int c;//my guesses
int inequality;//used to write if statements
for (int a = 0; a <= 10; a++)
{
cout << "Think about a number between 1-1000" << endl;//what console tells you
c = (big - small) / 2;//my guess will be the midpoint of the two numbers
while (big > small)//while the highest number is ALWAYS greater than the lowest number
{
cout << "Is your number less than, equal to, or greater than my guess? 1-less,2-equal,3-greater" << c << endl;
cin >> inequality;//you tell me whether my guess is too high, low, or equal
if (inequality == 1)//if you say it is too low...
{
small = c;//the smallest number is now my last guess
c = c - (big - small) / 2;//so, I'll take the midpoint of the CURRENT biggest and smallest number
}
else if (inequality == 2)//if you say it is equal...
{
cout << "Yay, I guessed your number." << endl;//cool.
}
else if (inequality == 3)//if you say it is too high...
{
big = c;//biggest number is now my guess
c = c + (big - small) / 2;//so, I'll take the midpoint of the CURRENT biggest and smallest number
}
}
}
system("pause");
return 0;//returns something in int main function
}
int main()
{
something();//so I can actually do code.
}
So my problem:
If I enter 1 after the console enters the first guess, I get 499, which is fine. After the second guess (where I enter 1), I get 249, which is also fine. However, the third guess after I enter 1 gets a random 681, so could someone help me?
It would be most appreciated if you did not rewrite the entire code for me, otherwise that is really suspicious when I turn it in. I am struggling because I do not have very good computer science background, so to improve, I need ideas mostly. Lastly, any way to make my code look a LITTLE more professional would be appreciated :)
Also, my for loop may be a bit off, I'm not sure.
When you calculate next number you need to change range
So you have first
small guess big
+---------+----------+
if user says too small, then the answer is above the guess, so in the range
big - guess and that is what you need to cut in half so instead of
c = c - (big - small)/2
guess = (big - guess) / 2 + guess
if user says too big then the answer is between guess and small
guess = (guess - small) / 2 + small
Try removing the c+ and c - terms from your midpoint calculations.
Edit: Also, try swapping the small = c and big = c statements in the two conditionals.
Your comments are mostly incorrect and that was my source of confusion.
In C++, I should write a program where the app detects which numbers are divisible by 3 from 1 till 10 and then multiply all of them and print the result. That means that I should multiply 3,6,9 and print only the result, which is 162, but I should do it by using a "While" loop, not just multiplying the 3 numbers with each other. How should I write the code of this? I attached my attempt to code the problem below. Thanks
#include <iostream>
using namespace std;
int main() {
int x, r;
int l;
x = 1;
r = 0;
while (x < 10 && x%3==0) {
r = (3 * x) + 3;
cout << r;
}
cin >> l;
}
Firstly your checking the condition x%3 == 0 brings you out of your while - loop right in the first iteration where x is 1. You need to check the condition inside the loop.
Since you wish to store your answer in variable r you must initialize it to 1 since the product of anything with 0 would give you 0.
Another important thing is you need to increment the value of x at each iteration i.e. to check if each number in the range of 1 to 10 is divisible by 3 or not .
int main()
{
int x, r;
int l;
x = 1;
r = 1;
while (x < 10)
{
if(x%3 == 0)
r = r*x ;
x = x + 1; //incrementing the value of x
}
cout<<r;
}
Lastly I have no idea why you have written the last cin>>l statement . Omit it if not required.
Ok so here are a few hints that hopefully help you solving this:
Your approach with two variables (x and r) outside the loop is a good starting point for this.
Like I wrote in the comments you should use *= instead of your formula (I still don't understand how it is related to the problem)
Don't check if x is dividable by 3 inside the while-check because it would lead to an too early breaking of the loop
You can delete your l variable because it has no affect at the moment ;)
Your output should also happen outside the loop, else it is done everytime the loop runs (in your case this would be 10 times)
I hope I can help ;)
EDIT: Forget about No.4. I didn't saw your comment about the non-closing console.
int main()
{
int result = 1; // "result" is better than "r"
for (int x=1; x < 10; ++x)
{
if (x%3 == 0)
result = result * x;
}
cout << result;
}
or the loop in short with some additional knowledge:
for (int x=3; x < 10; x += 3) // i know that 3 is dividable
result *= x;
or, as it is c++, and for learning purposes, you could do:
vector<int> values; // a container holding integers that will get the multiples of 3
for (int x=1; x < 10; ++x) // as usual
if ( ! x%3 ) // same as x%3 == 0
values.push_back(x); // put the newly found number in the container
// now use a function that multiplies all numbers of the container (1 is start value)
result = std::accumulate(values.begin(), values.end(), 1, multiplies<int>());
// so much fun, also get the sum (0 is the start value, no function needed as add is standard)
int sum = std::accumulate(values.begin(), values.end(), 0);
It's important to remember the difference between = and ==. = sets something to a value while == compares something to a value. You're on the right track with incrementing x and using x as a condition to check your range of numbers. When writing code I usually try and write a "pseudocode" in English to organize my steps and get my logic down. It's also wise to consider using variables that tell you what they are as opposed to just random letters. Imagine if you were coding a game and you just had letters as variables; it would be impossible to remember what is what. When you are first learning to code this really helps a lot. So with that in mind:
/*
- While x is less than 10
- check value to see if it's mod 3
- if it's mod 3 add it to a sum
- if not's mod 3 bump a counter
- After my condition is met
- print to screen pause screen
*/
Now if we flesh out that pseudocode a little more we'll get a skeletal structure.
int main()
{
int x=1//value we'll use as a counter
int sum=0//value we'll use as a sum to print out at the end
while(x<10)//condition we'll check against
{
if (x mod 3 is zero)
{
sum=x*1;
increment x
}
else
{
increment x
}
}
//screen output the sum the sum
//system pause or cin.get() use whatever your teacher gave you.
I've given you a lot to work with here you should be able to figure out what you need from this. Computer Science and programming is hard and will require a lot of work. It's important to develop good coding habits and form now as it will help you in the future. Coding is a skill like welding; the more you do it the better you'll get. I often refer to it as the "Blue Collar Science" because it's really a skillset and not just raw knowledge. It's not like studying history or Biology (minus Biology labs) because those require you to learn things and loosely apply them whereas programming requires you to actually build something. It's like welding or plumbing in my opinion.
Additionally when you come to sites like these try and read up how things should be posted and try and seek the "logic" behind the answer and come up with it on your own as opposed to asking for the answer. People will be more inclined to help you if they think you're working for something instead of asking for a handout (not saying you are, just some advice). Additionally take the attitude these guys give you with a grain of salt, Computer Scientists aren't known to be the worlds most personable people. =) Good luck.
I'm a beginner in C++ and am trying to find if there is a function that allows to "scan" an input in order to detect the type of equation entered.
Basically, what I'm trying to do is enter something like (a-b)^2 and the program would expand it to a^2-2*a*b+b^2 or enter ax^2+by+c and the program would give me a(x-α)+β.
What I have previously done is simply ask for what type of equation is going to be entered and then ask specifically what is each factor (like this) :
int a, a2;
int b, b2;
int inbetween;
cout << "Equation of type (ax+by)^2.\nPlease enter the factor of X : ";
cin >> a;
cout << "Please enter the factor of Y : ";
cin >> b;
a2 = a*a; //pow(a,2)
b2 = b*b; //pow(b,2)
inbetween = 2*a*b;
cout << "(" << a << "x + " << b << "y" << ")^2 = " << a2 << "x + " << inbetween << "xy + " << b2 << "y\n";
// (ax + by)^2 = a^2x + 2*a*b*xy + b^2y
But this is exactly what I do not want to do.
I'd like to know if there is a way to expand the input for any type of equation that the coded program supports.
I hope I am being clear enough, english isn't my main language I see that what I'm trying to communicate isn't really clear.
Your question is clear enough (it's actually a very interesting question IMO).
Yes, this is possible, but as far as I know there is no easy way of doing this ; you would have to program this yourself. I think your program is fine the way it is.
There is a whole area of mathematics called language theory which studies the sort of problem you just asked. To give you an idea of the solution of this sort of problem, the best way of solving this is writing your own grammar. You would have to elaborate the grammar rules formally before writing the parser, and implement the rules using regular expressions (then you would have two problems ;D ).
From the looks of your problem, this would require so much programming that, say, 95% of your code would be to decide what sort of expression it is and extract the values, and the remaining 5% would be just to expand or factorize. An excessive effort for a simple program, if you ask me.
I think Anthony D. has summed up the answer nicely, basically you're looking for a lexical analyzer and parser. If you are interested in learning more, it's worth directing you (and others that might find your question) towards the Yacc documentation. Although much of the documentation is Yacc specific, it is well written and detailed enough that it will help you reason through the different challenges and complexities of this problem. Plus, there are plenty of Yacc calculator examples that you can use as a reference if you eventually want to build a calculator.
I'm currently trying to solve a programming problem that involves different ranges of values that overlap. The task is to accept input, in E-notation, and that is where the overlap of range inevitably occurs.
I have 2 ranges that overlap at 1E-11. 1E-11 and lower and 1E-11 and higher
The output would be 1E-11 is either x or it is y. Programmatically i would solve it like this:
(X_MIN would be 1E-11 and X_MAX 1E-8)
(Y_MAX would be 1E-11 and Y_MIN 1E-13)
(lengthOfRange <= X_MIN) && (lengthOfRange >= Y_MAX) ?
cout << "This value entered indicates that it is x\n" :
cout << "It is y";
Expressed this way if i input IE-11 it shows me "This value entered indicates ..." but will never show me it is y (understandably - overlap!)
The other way around would be expressing it this way:
(lengthOfRange <= X_MIN) && (lengthOfRange != Y_MAX) ?
cout << "This value entered indicates that it is x\n" :
cout << "It is y";
The output would always be "... It is y ..." (Same difference - overlap!) There is no other determining factor that would tell range is x or y coming in to play there as of right now.
...
if (lengthOfRange <= X_MIN) && (lengthOfRange == Y_MAX)
{
cout << "The input indicates that it could be either x or y\n";
}
...
Even if i were to solve the problem in a way such as defining the range with different values, would in the end lead to the very same problem. I COULD define MIN and MAX as constants in lengthOfFrequency, which is totally different, bit then i would have to say: lengthOfFrequency = 1E-11; and voila same problem once again. 1 input 2 ranges that are technically different, getting the same one and only correct value in E-notation.
Is there a way around this without involving to simply say input is either x || y? Which it is technically of course, and if it were to be solved physically there are ways of telling it apart that 1E-11 is not 1E-11 though it is. (I hope i make sense here). But, again, ... is there such way, and how would i go about writing it? (Not asking for code specifically though it would be highly welcome, just a pointer in the right direction.) Or should i rather go with saying input is either x || y?
Thanks in advance for any answer!
**Minimum Complete Code:**
#include <iostream>
using std::cout;
using std::cin;
int main()
{
/* Constants for ranges, min and max */
const double X_RAYS_MIN = 1E-13,
X_RAYS_MAX = 1E-11,
Y_RAYS_MIN = 1E-11,
Y_RAYS_MAX = 1E-8,
Z_RAYS_MIN = 1E-7,
Z_RAYS_MAX = 3.8E-7;
double lengthOfRange;
/* Test output and validation */
cout << "Enter value in scientifc notation: ";
cin >> lengthOfRange;
/* X_RAYS_MIN < is 1E-14, 1E-15, 1E-16 etc. > 1E-12, 1E-11 etc.. */
if (lengthOfRange >= X_RAYS_MIN && lengthOfRange <= X_RAYS_MAX)
{
cout << "X_RAYS\n";
}
else if (lengthOfRange >= Y_RAYS_MIN && lengthOfRange <= Y_RAYS_MAX)
{
cout << "Y_RAYS\n";
}
system("pause");
return 0;
}
Output is: 1E-10 is Y_RAYS, 1E-9 is Y_RAYS, 1E-11 X_RAYS, 1E-12 X_RAYS
Somehow i found the solution for my problem myself without going any roundabout ways ... By hovering over the 1E-13:
X_RAYS_MIN = 1E-13
VS showed me 1.(numberofzeros)3E-13, and guess what ... if instead the input for 1E-11 is 2E-11, the output for X_RAYS becomes Y_RAYS ... so the problem "magically" solved itself ... lucky me i guess ... :)
This question already has answers here:
Making a square() function without x*x in C++
(7 answers)
Closed 4 years ago.
I'm a beginner in programming and trying to learn C++ by the book Programming principles and practice using C++. In some parts of the book there are little exercises that you can try to do, one of this exercises is about calculating the square of a number, here is what my book says :
Implement square() without using the multiply operator, that is, do the x * x by repetead addition (start a variable result to 0 and add x to it x times).
I've already found a solution for this program but my first tentative was something like this :
#include <iostream>
int main()
{
int a = 0;
std::cout << "Enter an integer value : ";
std::cin >> a;
while (a < a * a)
{
a += a;
std::cout << a << "\n";
}
}
I know this code is wrong but I can't understand the output of the progam, if I enter 5 the program prints 10 20 30 40 50 until 8000, why the for loop doesn't stop when a is greater than its square ? I'm just curious to undersant why
Using multiplication when trying to avoid multiplication seems broken. What about this:
int r = 0;
for (int n = 0; n < a; ++n) {
r += a;
}
why the for loop doesn't stop when a is greater than its square ?
Because it never is. If you compare the graph of y=x^2 against the graph of y=x, you will see that the only time y=x is above, is when 0 < x < 1. That's never the case for integers1. Now, since we're talking about computers with limited storage here, there is a thing called overflow, which will cause a very large number to become a very small number. However, signed integer overflow is undefined behavior in C++. So once your loop gets to the point where overflow would happen, you cannot rely on the results.
1. Note that your loop is not set to stop just when a is greater than its square, but when it is greater than or equal to its square. So, your loop will actually stop if a is 0 or 1.