【问题标题】:Finding prime numbers and then putting the prime numbers into an output file查找素数,然后将素数放入输出文件
【发布时间】:2017-07-07 23:34:16
【问题描述】:

所以我有一个班级作业,我必须向用户询问 1 到 3000 之间的整数。然后我的程序应该能够判断该整数是否为质数。最后,我必须将该整数放入文件中,但前提是它是质数。但我的问题是我的语法,我不确定它是否正确(实际上显然这不是因为我不断收到错误)。是否可以在函数中打开文件?如果是这样,它会成为一个参数吗? 我一直在阅读我的教科书并尽可能多地搜索一些指导,但我仍然感到迷茫。任何建议都会有所帮助。

编辑:就数字而言,我的逻辑是有效的,但是当我添加要写入文件的代码时,我现在遇到了错误。

这两个错误是

C2440 初始化:无法从常量 char 转换为 int(第 18 行)

C2079 myfile: 使用未定义的类'std::basic_fstream char,std::char_traits>'

这是我目前的代码!

    // Project 5.cpp : Defines the entry point for the console application.
    //


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

using namespace std;

//functions

void prime(int x);

//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");

int main()

{


    do
    {
        cout << "Enter an integer between 1 and 3000 \n";
        cin >> x;
        if (x == 1)
        {
            cout << x << " is not a prime number.\n";
        }
       else if (x < 1 || x>3000)
        {
            cout << x << " is an invalid number. \n";
        }
        else
        {

            prime(x);
        }

        cout << "Do you want to enter another number? Y/N \n";
        cin >> answer;
    } while (answer == 'y' || answer == 'Y');

    myfile.close();

    return 0;
}

void prime(int x)
{


    if (x == 2)
    {
        cout << "Yes, " << x << " is Prime\n";
    }
    else
    {
        for (i = 2; i < x; i++)
        {
            if (x%i == 0)
            {
                cout << x << " is not a prime number\n";
                break;
            }
        }
        if (x == i)
        {
            cout << "Yes, " << x << " is Prime\n";
            myfile << x ;

        }
    }
}

【问题讨论】:

  • 请注意:除 2 外,每个素数都是奇数。这需要一些优化...
  • “实际上显然这不是因为我不断收到错误” - 嗯......发布这些错误怎么样?我在没有#include "stdafx.h" 的情况下在 Code::Blocks 上运行了您的代码,它运行良好。 @Garmekain,关于优化-实际上有更多优化方法,但这与问题无关。我强烈建议您使用outputFile.good() 方法测试文件打开过程是否成功。如果打开成功,则返回 true。在您发布错误后,我将继续回答问题并为类似的未来项目提供一些建议
  • @Fureeish 这就是为什么它只是一个小便条。
  • 仅供参考,如果将答案转换为小写或大写,则只需进行一次比较。见std::toupperstd::tolower
  • 在没有 stdafx.h 标头的 GCC 中为我工作,如果行为是输入数字并且如果它是素数,则将其写入 castor_primes.txt 文件的第一个位置(如果没有则创建它不存在)。正如@Fureeish 指出的那样,您应该发布您遇到的错误。

标签: c++ function file-io output primes


【解决方案1】:

#include "stdafx.h" 在使用 Microsoft Visual Studio 时包含一个预编译的头文件。检查该文件是否存在以及是否正确(取决于您看到的错误)。

没有理由将 outputFile 传递给 prime() 函数,因为您在函数中打开和关闭它。虽然如果你这样做它就很好。

它是函数调用的参数(如果这是您的问题)并且是全局变量,因为它是在 main() 函数之外定义的。

正如其他人建议的那样,如果上述 #include "stdafx.h" 被删除,代码将起作用,但我不确定这将如何影响 Visual Studio 中的编译。

【讨论】:

  • 投反对票。这不是消除 OP 错误的有效答案。
  • 正确,但它确实回答了有关在函数中打开文件的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
相关资源
最近更新 更多