简体   繁体   中英

Simple C++ Code giving wrong answers

If I input 299,399,10,5 in order, the computer should give me an answer of 5.But it gives me -5. Why not 5? And this confuses me. Help!!

#include "stdafx.h"
#include <iostream>

int add(int x, int y)
{
    int a=x-y;
    return a;
}

int x(int a)
{
    std::cin >> a;
    return a;
}

int y(int a)
{
    std::cin >> a;
    return a;
}

int main()
{
    int a;
    int b;
    std::cin >> a;
    std::cin >> b;
    std::cout << add(x(a), y(b));
    return 0;
}

The compiler is free to call x(a) and y(b) in any order it likes. If you write this:

int c = x(a);
int d = y(b);
std::cout << add(c, d);  

It should work.

Oh, and please don't name subtraction functions 'add'... :)

In the statement

std::cout << add(x(a), y(b));

the order in which x(a) and y(b) are called is unspecified by the C++ standard. Which means x() might be called before y() , or it might not.

You are assuming x() is called first. If y() is called first, you will get the results you see. The compiler is correct either way (that's essentially what "unspecified" means in the standard, in this case).

If the order of such things matter, you need to force the issue by ensuring the right order. For example;

a = x(a);
b = y(b);
std::cout << add(a,b);

There are also concerns as x() and y() do not use the values passed from the caller. Unless they are a placeholder for something else which the function will need, there is no reason the caller should have to pass them.

And having a function named add() that does subtraction .... wash your mouth out with soap.

因为x = 5且y = 10,所以5-10 = -5

In your question first Y(a) function executes and than x(a) function. As C/C++ is a right left executable function. Whenever you mention function inside a function example c=(X(a),Y(b)); In this example first your Y(a) function is executed and then your X(a) function. your program is correct but need a clarity over which function is executing. Hence I have updated your code as below.

int add(int x, int y)
{
  std::cout<<"Executing add function";
  std::cout<<"x="<<x<<" y="<<y;
  int a=x-y;
  return a;
}

int x(int a)
{
  std::cout<<"Executing X function";
  std::cin >> a;
  std::cout <<"X will return "<<a;
  return a;
}


int y(int a)
{
  std::cout<<"Executing Y Function\n";
  std::cin >> a;
  std::cout <<"y will return "<<a;
  return a;
}

 int main()
{
  int a;
  int b;
  std::cin >> a;
  std::cin >> b;
  std::cout << add(x(a), y(b));
  return 0;
}

Now you can easily find out which function is executing and can provide input accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM