C ++的新手,我在调用我的函数时遇到了麻烦

时间:2017-01-13 22:40:01

标签: c++ function

#include <iostream>
#include <math.h>

using namespace std;

int Square(int num, int& Answer);
int Triangle(int num);

int main(int argc, char **argv)
{
    int num = -1;
    int Answer;
  //Prompts the user for the length of the sides and doesnt stop until they     enter a valid input
while(num >= 6 || num <= 1){
    cout<<"Enter a number from 1 to 6: ";

    cin>>num;
    }

Square(int num, int& Answer);
Triangle(int num, int&Answer);


}

int Square(int num, int& Answer){
    Answer = num * num;
    cout<<Answer;
}

int Triangle(int num, int& Answer){
    Answer = .5 * (num * num);
    cout<<Answer;
}

我不确定我做错了什么,但我一直在犯的错误是,预期在&#39; int&#39;

之前的初级表达

这是错误的位置,它出现在每个int

的实例上
Square(int num, int& Answer);
Triangle(int num, int&Answer);

1 个答案:

答案 0 :(得分:2)

这不是如何调用函数:

Square(int num, int& Answer);
Triangle(int num, int&Answer);

更正:

Square  (num, Answer);
Triangle(num, Answer);
  • 还包括cmath而不是math.h:

    #include <cmath>
    
  • 函数三角形也只接受一个参数,你传递两个参数:

    Triangle(int num, int&Answer);
    

所以要么传递num或回答。

  • 另一件事:为什么将Answer作为参数传递?

您只能传递num,每个函数的返回值将其存储在Answer中。一个例子是这样的:

#include <iostream>
//#include <cmath> // if you don't need it don't include it
using namespace std;

int Square  (int num); // Square needs only parameter and returns the result in return value
int Triangle(int num); // the same as above

int main(int argc, char **argv)
{
    int num = -1;
    int Answer;
  //Prompts the user for the length of the sides and doesnt stop until they     enter a valid input
    while(num >= 6 || num <= 1){
        cout<<"Enter a number from 1 to 6: ";
        cin >> num;
    }

    Answer = Square(num); // here I assign the return value of Square to Answer
    cout << "Squre( " << num << " ) = " << Answer << endl;  // check
    Answer = Triangle(num); // the same as above
    cout << "Triangle( " << num << " ) = " << Answer << endl;

    return 0;
}

int Square(int num){
    return (num * num); // store the result in return address
}

int Triangle(int num){
     return ( .5 * (num * num));
}