【问题标题】:How to make the outcome of a boolean function to output a certain statement when the boolean is TRUE or FALSE in the main (c++)?当布尔值在main(c ++)中为TRUE或FALSE时,如何使布尔函数的结果输出某个语句?
【发布时间】:2019-07-28 21:42:15
【问题描述】:

问题

我正在尝试编写一个可以输出所有数字素因子的程序。我首先创建了一个函数来检查一个因子是否为素数:

bool checkPrime() {
for (x = 1; x <= i; ++x) {
    if (x % i != 0) {
        return 1;
    }
    else {
        return 0;
    }
}

主要

int main() {

cout << "Enter any positive number: " << endl;
cin >> n;

cout << "Prime Factors of " << n << " are: " << endl;
for (i = 1; i <= n; ++i) {
    if (n % i == 0) {
        for (x = 1; x <= i; ++x) {
                cout << i << "   ";
        }
}
cout << "\n";
system("pause");

}

问题

如何实现我的“checkPrime”函数来检查我是否运行:

cout << i << "   ";

【问题讨论】:

  • 无法通过找到一个不完全除法的单个数字来识别素数。仔细检查您的checkPrime(),它总是在检查x 为1 后返回。它应该以i 作为参数。我想你的意思是i%x 不是x%i

标签: c++ function boolean factors


【解决方案1】:

我认为问题在于将checkPrime() 函数的布尔返回值打印为truefalse。我不会在这个答案中讨论 checkPrime() 函数的正确性。但出于您的目的,请使用以下内容。

std::cout &lt;&lt; std::boolalpha &lt;&lt; checkPrime() &lt;&lt; std::noboolalpha &lt;&lt; std::endl;

参考:https://en.cppreference.com/w/cpp/io/manip/boolalpha

我没有调查你的 checkPrime() 函数,但理想情况下它应该接受 n 作为参数。

【讨论】:

    【解决方案2】:
    1. 更改 checkPrime 以接受输入。
    2. 修复实施。当前的实现不正确。
    3. main中添加对函数的调用,并根据函数的返回值输出数字。

    bool checkPrime(int i)
    {
       // 1 and 2 are primes
       if ( i < 2 )
       {
          return true;
       }
    
       if ( i % 2 == 0 )
       {
          return false;
       }
    
       // Check with only odd numbers.
       // Division by even numbers is not necessary.
       // Even numbers greater than 2 are not prime numbers.
       // Also, you don't need to check for division by numbers greater than sqrt(i)
    
       for (x = 3; x*x <= i; x +=2 )
       {
          if ( i % x == 0)
          {
             return false;
          }
       }
    
       return true;
    }
    

    main:

    for (i = 1; i <= n; ++i)
    {
       if (n % i == 0 )
       {
          if ( checkPrime(i) )
          {
             cout << i << "   ";
          }
       }
    }
    

    您可以将两个if 语句合并为一个if 语句。

    for (i = 1; i <= n; ++i)
    {
       if (n % i == 0 && checkPrime(i) )
       {
          cout << i << "   ";
       }
    }
    

    【讨论】:

    • 所以我完全理解你在这里所做的一切,除了我不知道你为什么在 checkPrime() 函数中的 for 语句的条件下执行“x*x”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多