繁体   English   中英

个人图书馆,号码正负

[英]Personal library, number positive or negative

使用个人库在 C++ 中实现一个应用程序,该应用程序根据用户所做的选择来确定一个数是正数还是负数,或者一个数是否为素数。 这是主要代码:

#include <iostream>
#include "libreria.cpp"
using namespace std;
int s;
int main()
{
    int num1,cont;
    cout<<"\n 1) Positive ";
    cout<<"\n 2) Prime ";
    cout<<"\n 3) Exit ";
    cout<<"\n Choose: ";

    do
    {
        cin>>s;
        switch (s)
        {
        case 1:
            cout<<"\nInsert the number: ";
            cin>>num1;
            bool sepos(int numb);
            if (bool sepos(int numb)==1)
            {
                cout<<"\nIl numero "<<num1<<" e' positive";
            }
            else 
            {
                cout<<"\nIl numero "<<num1<<" e' negative";
            }
        break;
        case 2:
        break;
        }
    } while (s!=3);
    return 0;   
}

图书馆是:

bool sepos(int numb)
{
    if(numb>=0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

现在,我想看看这个数字是否为正数。 但是应用程序不起作用,我遇到了很多错误。

[Error] function 'bool sepos(int)' is initialized like a variable 
[Error] expected primary-expression before '==' token 
[Error] expected '=' before '==' token 
[Warning] declaration of 'bool sepos(int)' has 'extern' and is initialized

我注意到你做错了几件事。

第一个是: if (bool sepos(int numb)==1)您正在尝试将 bool 值( true 或 false )与数字进行比较。 是的,C++ 将 1 和 0 视为真或假,但您的函数已经返回真或假。

#include <iostream>
#include "libreria.cpp"
using namespace std;
int s;
int main()
{
  int num1,cont;
  cout<<"\n 1) Positive ";
  cout<<"\n 2) Prime ";
  cout<<"\n 3) Exit ";
  cout<<"\n Choose: ";

  do
  {
    cin>>s;
    switch (s)
    {
    case 1:
        cout<<"\nInsert the number: ";
        cin>>num1;
        if (sepos(int numb))
        {
            cout<<"\nIl numero "<<num1<<" e' positive";
        }
        else 
        {
            cout<<"\nIl numero "<<num1<<" e' negative";
        }
    break;
    case 2:
    break;
    }
  } while (s!=3);
    return 0;   
}

另一个问题是:你的函数bool sepos(int numb)被声明为返回一个布尔值,你不必强制转换它。

numb>=0返回 true 或 false,您不必明确返回这些值。

bool sepos(int numb)
{
    return numb>=0;
}

我的建议:试着多学一点语言的语法,可以避免很多错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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