Page 1 of 1

write a C++ please

Posted: Sat Oct 13, 2018 12:17 am UTC
by Tonny91
Write a C ++ program to enter two integers x, y, then calculate: p = x * y, s = x + y, q = s2 + p (s-x) * (p + y) and print the result.

Re: write a C++ please

Posted: Sat Oct 13, 2018 9:02 am UTC
by phlip
The forums aren't here to do your homework for you... how about you talk more about what you've tried so far, and what you're getting stuck on?

Re: write a C++ please

Posted: Mon Oct 15, 2018 1:18 am UTC
by gd1
Stack exchange will probably give you the same answer as above by the way.

Some hints:
You need to declare variables for each of x, y, p, q, s, and s2.
You then need to print out something asking for input which you then store into x and y.
Then you need to perform those calculations afterwards.

Re: write a C++ please

Posted: Mon Oct 15, 2018 1:45 pm UTC
by Soupspoon
I think OP has "s2" marked down wrong anyway, and meant "s²".

Just one of several clues that OP might not be serious about this problem, or able to deal with it. Please, OP, do prove me wrong by being more than a 1-post Henry.

In the meantime, let's try it in FORTH, instead.

Code: Select all

: C SWAP OVER OVER * OVER OVER + ROT SWAP OVER - >R -ROT OVER OVER + <R * * -ROT + DUP * +. ;

I think that'd do it, by invoking "C x y", but I may be mixing my dialects or totally off-piste, as I don't have a FORTH machine I can easily poke at the moment, to resolve typos and thinkos.

edit: No, wait, totally wrong.

More pencil and paper later..?:

Code: Select all

: C SWAP OVER OVER * OVER OVER + * -ROT DUP -ROT + DUP ROT - ROT * SWAP DUP * + . ;

I'm really out of practice.

(Conversion 'back' to C++ is also left as an exercise to the reader.)

Re: write a C++ please

Posted: Mon Oct 15, 2018 2:14 pm UTC
by commodorejohn
Soupspoon wrote:In the meantime, let's try it in FORTH, instead.

(Conversion 'back' to C++ is also left as an exercise to the reader.)

I have a new favorite method for dealing with "please do my homework for me" posts.

Re: write a C++ please

Posted: Mon Oct 15, 2018 3:36 pm UTC
by Tub
You know, OP requested C++, so why don't you post C++ solutions?

Code: Select all

#include <iostream>
#include <stdexcept>


// We need to model the positive integers in a portable and standard compliant way.
// We chose to use Peano Numbers for the following reason:
//  * There are no overflows, hence there's no undefined behaviour, reducing the chance of bugs or security issues.
//  * They're portable, requiring no concerns for native integer sizes, endianess or binary complements.
//  * They require no additional headers, improving compilation speed.
class Number {
   public:
      // Initialize a new Zero
      static Number *Zero() {
         return new Number{nullptr};
      }
      // Initialize a new Successor of an existing Number
      static Number *Successor(Number *predecessor) {
         return new Number{predecessor};
      }
      // Returns true if the number is Zero
      bool isZero() {
         return predecessor == nullptr;
      }
      Number *predecessor;
};

// Add two numbers
Number *add(Number *a, Number *b) {
   while (!b->isZero()) {
      a = Number::Successor(a);
      b = b->predecessor;
   }
   return a;
}

// Return the difference between two numbers
Number *difference(Number *a, Number *b) {
   while (true) {
      if (b->isZero())
         return a;
      if (a->isZero())
         throw std::runtime_error("Difference is negative");
      a = a->predecessor;
      b = b->predecessor;
   }
}

// Multiply two numbers
Number *multiply(Number *a, Number *b) {
   if (a->isZero() || b->isZero())
      return Number::Zero();

   Number *result = Number::Zero();
   while (!b->isZero()) {
      result = add(result, a);
      b = b->predecessor;
   }
   return result;
}

// Compare two numbers. Returns -1 if a is smaller, 0 if equal, 1 if b is smaller
int compare(Number *a, Number *b) {
   while (true) {
      if (a->isZero() && b->isZero())
         return 0;
      if (a->isZero())
         return -1;
      if (b->isZero())
         return 1;
      a = a->predecessor;
      b = b->predecessor;
   }
}

// Read a Number
Number *readNumber() {
   Number *number = Number::Zero();
   Number *ten = Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Successor(Number::Zero()))))))))));
   while (true) {
      char c;
      std::cin.get(c);
      if (c >= '0' && c <= '9') {
         // If the user has typed "123" and then adds a "4", our new number is 123 * 10 + 4 = 1234
         number = multiply(number, ten);
         Number *digit = Number::Zero();
         for (char i = c; i > '0'; i--) {
            digit = Number::Successor(digit);
         }
         number = add(number, digit);
      }
      else {
         return number;
      }
   }
}

// Write a Number to an output stream
std::ostream &operator<<(std::ostream &ostream, Number *number) {
   Number *one = Number::Successor(Number::Zero());
   Number *two = Number::Successor(one);
   Number *three = Number::Successor(two);
   Number *four = Number::Successor(three);
   Number *five = Number::Successor(four);
   Number *six = Number::Successor(five);
   Number *seven = Number::Successor(six);
   Number *eight = Number::Successor(seven);
   Number *nine = Number::Successor(eight);
   Number *ten = Number::Successor(nine);

   // Find a number 10^x that is larger than our number
   Number *highest_digit = ten;
   while (compare(number, highest_digit) >= 0)
      highest_digit = multiply(highest_digit, ten);

   Number *current_digit = highest_digit;
   while (!current_digit->isZero() && !current_digit->predecessor->isZero()) {
      // Find the next lower number 10^x
      Number *next_digit = one;
      Number *next_digit2 = next_digit;
      while (compare(current_digit, next_digit) > 0) {
         next_digit2 = next_digit;
         next_digit = multiply(next_digit, ten);
      }
      current_digit = next_digit2;

      char output_char = '?';
      Number *output_number = Number::Zero();
      if (compare(number, multiply(nine, current_digit)) >= 0) {
         output_char = '9';
         output_number = nine;
      }
      else if (compare(number, multiply(eight, current_digit)) >= 0) {
         output_char = '8';
         output_number = eight;
      }
      else if (compare(number, multiply(seven, current_digit)) >= 0) {
         output_char = '7';
         output_number = seven;
      }
      else if (compare(number, multiply(six, current_digit)) >= 0) {
         output_char = '6';
         output_number = six;
      }
      else if (compare(number, multiply(five, current_digit)) >= 0) {
         output_char = '5';
         output_number = five;
      }
      else if (compare(number, multiply(four, current_digit)) >= 0) {
         output_char = '4';
         output_number = four;
      }
      else if (compare(number, multiply(three, current_digit)) >= 0) {
         output_char = '3';
         output_number = three;
      }
      else if (compare(number, multiply(two, current_digit)) >= 0) {
         output_char = '2';
         output_number = two;
      }
      else if (compare(number, multiply(one, current_digit)) >= 0) {
         output_char = '1';
         output_number = one;
      }
      else {
         output_char = '0';
         output_number = Number::Zero();
      }

      ostream << output_char;
      number = difference(number, multiply(output_number, current_digit));
   }

   return ostream;
}


int main() {
   // Input x and y
   std::cout << "Enter X: ";
   Number *x = readNumber();
   std::cout << "Enter Y: ";
   Number *y = readNumber();

   std::cout << "x = " << x << ", y = " << y << std::endl;

   // p = x * y
   Number *p = multiply(x, y);
   std::cout << "p = x * y = " << p << std::endl;

   // s = x + y
   Number *s = add(x, y);
   std::cout << "s = x + y = " << s << std::endl;

   // q = s^2 + p * (s - x) * (p + y)
   Number *q = add(multiply(s, s), multiply(p, multiply(difference(s, x), add(p, y))));
   std::cout << "q = s^2 + p * (s - x) + (p + y) = " << q << std::endl;

   return EXIT_SUCCESS;
}

I considered implementing the pure recursive variants, but this isn't StackOverflow.

Re: write a C++ please

Posted: Mon Oct 15, 2018 3:53 pm UTC
by DavidSh
That's all very nice, but the original specification was for "integers", not "positive integers". You need a new class, and take care not to distinguish between positive zero and negative zero.

Re: write a C++ please

Posted: Mon Oct 15, 2018 5:03 pm UTC
by Flumble
Did I do good? :mrgreen:

Code: Select all

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

void make_temp_file(string fileName) {
  ofstream tmp(fileName.c_str());

  tmp << "x = read()" << endl
      << "y = read()" << endl
      << "p = x*y" << endl
      << "s = x + y" << endl
      << "q = s^2 + p * (s-x) * (p + y) " << endl
      << "print q" << endl
      << "quit \n"; //don't forget to call quit, because otherwise bc will keep its prompt open and it probably won't exactly match the specifications
}

main ()
  {
  std::string fname;
  fname = "/tmp/some_exercise";
  make_temp_file(fname); //make the temp file
  return system(((string)"bc -q "+fname).c_str());
  }


On a serious note: it's unfortunate that tmpfile() never got a C++ey version, so to turn it into an iostream you need some boilerplate code.

Re: write a C++ please

Posted: Mon Oct 15, 2018 6:33 pm UTC
by commodorejohn
I have a new new favorite method for dealing with "please do my homework for me" posts.

Re: write a C++ please

Posted: Mon Oct 15, 2018 10:18 pm UTC
by Tub
Flumble wrote:Did I do good?

You're mixing std::endl with "\n". The standard does not guarantee those to be equal. It's not going to be portable to my upcoming operating system, which uses utf8 emojis instead of ASCII control characters or ANSI escape sequences.

Otherwise, I see no portability issues.
Flumble wrote:On a serious note: it's unfortunate that tmpfile() never got a C++ey version, so to turn it into an iostream you need some boilerplate code.

An 8 year old forum post that starts with "I just wanted to play around with this kind of stuff" is a reliable source for any kind of boilerplate code you need, but I'd like to offer some alternatives anyway.

Some stdlibs offer premade implementations, e.g. __gnu_cxx::stdio_filebuf can be constructed using a posix file handle or a FILE *.

For more portability, boost has the file_descriptor and stream classes, which combine into that thing you want.

Re: write a C++ please

Posted: Mon Oct 15, 2018 11:48 pm UTC
by Flumble
All I can find on endl boils down to "Inserts a newline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush()." The stream is then supposed to convert '\n' to the appropriate byte sequence. (I could change the code to say "\r\n" to make it wronger, but I don't know if bc likes windows line endings.)

Tub wrote:An 8 year old forum post that starts with "I just wanted to play around with this kind of stuff" is a reliable source for any kind of boilerplate code you need

True, it just looked like the most generic and concise (even if it's not well implemented) solution in a quick search. As you can probably guess, I totally forgot to add boost to the keywords. :oops:

Tub wrote:Some stdlibs offer premade implementations, e.g. __gnu_cxx::stdio_filebuf can be constructed using a posix file handle or a FILE *.

I saw a couple of those among the results, but anything starting with two underscores scares me.* Then again, only now do I realize __gnu_cxx sounds pretty generic—do I understand correctly that GCC populates that namespace on every platform?


*except if it's python, then I only get scared when an answer on stackoverflow suggests a magic method as a workaround.

Re: write a C++ please

Posted: Tue Oct 16, 2018 12:21 am UTC
by Thesh
Why can't you just do what the OP asked? It's not that big of a deal.

Spoiler:

Code: Select all

a C++ please

Re: write a C++ please

Posted: Tue Oct 16, 2018 2:45 pm UTC
by SuicideJunkie
Rather than writing a C++ from scratch, I recommend forking GCC instead.
It'll save you so much time.

Re: write a C++ please

Posted: Wed Oct 17, 2018 1:54 am UTC
by pogrmman
I'll leave the transformation to C++ as an exercise for the reader. As a bonus, it works with any numbers, not just integers :p
Spoiler:
The code:

Code: Select all

(define a-c++ (lambda () (display "x: ") ((lambda (x) (display "y: ") ((lambda (y) ((lambda (p) ((lambda (s) ((lambda (q) (display "p: ") (display p) (newline) (display "s: ") (display s) (newline) (display "q: ") (display q) (newline)) (+ (square s) (* (* p (- s x)) (+ p y))))) (+ x y))) (* x y))) (read))) (read))))

Sample output:

Code: Select all

> (a-c++)
x: 1
y: 2
p: 2
s: 3
q: 25
> (a-c++)
x: 1.4
y: 2.6
p: 3.64
s: 4.0
q: 75.05536
> (a-c++)
x: 1/8
y: 13/18
p: 13/144
s: 61/72
q: 10655/13824
> (a-c++)
x: 4+3i
y: 6
p: 24+18i
s: 10+3i
q: 2467+5892i

Re: write a C++ please

Posted: Fri Oct 19, 2018 4:10 am UTC
by gd1
The code:

Code: Select all

#include <iostream>
using namespace std;
int main()
{
   int x, y, p, s, q;
   cout<<"Enter x and y : ";
   cin>>x>>y;
   p = x * y;
   s = x + y;
   q = (s * s) + (p*(s - x)) * (p + y);
   cout<<"The value stored in q is : "<<q;
   
   return 0;
}


I figure it's already been a bit anyways.

Int x, y, p, s, q;
This declares the variable x y p s and q so you can use them.

cout<<"Enter x and y : ";
This tells the program to print out the stuff in "".

cin>>x>>y;
This stores what you just entered into the variables x and y that you declared earlier.

p=x*y;
This multiplies the values stored in x and y then assigns that value to the variable p.

s=x+y;
This is one letter away from being inappropriate. It also adds the values of x and y together and then stores them in the variable s.

q=(s*s)+(p*(s-x))*(p+y);
This is the final calculation that does some mathematics and stores the result in the variable q.

cout<<"The value stored in q is : "<<q;
This prints out the stuff in "" and then the value of q right afterwards.

I used code from this website: http://www.cppforschool.com/assignment/library-functions-sol/area-triangle.html and adapted it to do what you requested because I haven't done c++ in a while and c is somewhat similar.

If you want to print out all 3 results

cout<<"The values stored in p s and q are : "<<p;
cout<<" "<<s;
cout<<" "<<q;

Re: write a C++ please

Posted: Fri Oct 19, 2018 7:23 am UTC
by PM 2Ring
gd1 wrote:q=(s*s)+p(s-x)*(p+y);
This is the final calculation that does some mathematics and stores the result in the variable q.

You should fix that typo. p isn't callable.

Re: write a C++ please

Posted: Fri Oct 19, 2018 1:32 pm UTC
by gd1
PM 2Ring wrote:
gd1 wrote:q=(s*s)+p(s-x)*(p+y);
This is the final calculation that does some mathematics and stores the result in the variable q.

You should fix that typo. p isn't callable.


Did you mean p*(s-x) ?

Re: write a C++ please

Posted: Fri Oct 19, 2018 1:38 pm UTC
by Soupspoon
I was looking forward to the definition of an overloaded version of p that was a single-use funtion, but I'm less sure how one might do that in C++ than in some other languages I could mention. (I wonder if one can take all variable tokens and automagically generate token() functions, without some form of token()=functionise('token').

Though developing a whole 'plaintext function' parser, a la Google, would be an interesting exercise. Especially if you can top-load it with the q= one and then you answer its demands for "So what does p=, s=, and did you mean to define s2=?", as it encounters such questions, then gradually it accomplishes it.

(If you do write that, try and get it so that it can work on the Drake Equation, perhaps by looking up the values on its own, at least once you tell it what you mean by them. ;))

Re: write a C++ please

Posted: Fri Oct 19, 2018 1:39 pm UTC
by Soupspoon
gd1 wrote:Did you mean p*(s-x) ?
Who? You did mean it, and you've corrected it.

(Inefficiently, you don't need to do (a*(b))*c…)

((Strangely, I saw the p() version, and the first reply to which I was non-quotingly replying, but edit times indicate that I shouldn't have!)) Whoops, misread the tens-of-minutes.