RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1046635
Accepted
Ghost
Ghost
Asked:2020-11-16 00:21:49 +0000 UTC2020-11-16 00:21:49 +0000 UTC 2020-11-16 00:21:49 +0000 UTC

处理文件(读取和写入)

  • 772

需要使用随机数生成器在文件中生成 10 个数字。找到文件中最大和最小数字的总和。从 0 到 30 的数字。

问题:

该文件位于项目的根目录

#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>

using namespace std;

int main()
{
    setlocale(LC_ALL, "ru");
    srand(time(NULL));
    int res = 0, i, min, max, num;
    ofstream File("doc.txt");
    if (!File) {
        cout << "Ошибка: файл не найден" << endl;
        return 1;
    }
    for (i = 0; i < 10; i++) {
        num = rand() % 30;
        File << num;
    }
    File.close();
    ifstream File2("doc.txt");
    int get, k;
    int A[1000];
    if (!File2) {
        cout << "Файл не найден!" << endl;
    }
    else {
        k = 0;
        while (File2 >> get) {
            A[k++] = get;
        }
        max = A[0];
        min = A[0];
        for (i = 0; i < 10; i++) {
            if (max < A[i])
                max = A[i];
            if (min > A[i])
                min = A[i];
        }
        cout << "Максимальное значение массива: " << max << endl;
        cout << "Минимальное значение массива: " << min << endl;
        res = max + min;
    }
    File2.close();
    cout << "Результат: " << res << endl;
    system("pause");
    return 0;
}
c++
  • 3 3 个回答
  • 10 Views

3 个回答

  • Voted
  1. Harry
    2020-11-16T00:44:12Z2020-11-16T00:44:12Z

    并且您不想分隔显示的数字,例如,用空格?还是从新的线路?而不是将它们雕刻成一个大数字?

    比方说

    for (i = 0; i < 10; i++) {
        num = rand() % 30;
        File << num << " ";
    }
    

    如果你不依赖“魔常数”10,而是这样做:

        k = 0;
        while (File2 >> get) {
            A[k++] = get;
        }
        cout << "Считано " << k << " чисел" << endl;
        max = A[0];
        min = A[0];
        for (i = 0; i < k; i++) {
    

    错误将立即显而易见......

    • 5
  2. Best Answer
    AR Hovsepyan
    2020-11-16T00:48:10Z2020-11-16T00:48:10Z

    这就是为什么您需要将读取的内容存储在数组中的原因,目前尚不清楚。您需要做的就是在这里:

    //учитывая, что ваши числа от 0 до 30
    int max = -1, min = 31,
        n{}, cur{};
    while (File2 >> cur && n < 10) {
        if (max < cur) max = cur;
        if (min > cur) min = cur;
        ++n;
    }
    cout << "minel " << min
         << "\nmaxel " << max
         << "\nsum = " << min + max;
    

    是的,您在写入文件时也犯了一个错误(请参阅 Harry}

    • 1
  3. user326165
    2020-11-16T04:47:23Z2020-11-16T04:47:23Z
    #include <iostream>
    #include <vector>
    #include <functional>
    #include <random>
    #include <cstdint>
    #include <filesystem>
    #include <iterator>
    #include <fstream>
    
    
    static decltype(auto) GetRandomEngine(int64_t bottomBorder, int64_t upperBorder) noexcept
    {
        std::mt19937_64 generator(std::random_device{}());
        std::uniform_int_distribution<> uid(bottomBorder, upperBorder);
    
        return std::bind(uid, generator);
    }
    
    
    static std::vector<int64_t> GetVectorWithEntropy(uint64_t size, int64_t bottomBorder, int64_t upperBorder) noexcept
    {
        auto random_generator{GetRandomEngine(bottomBorder, upperBorder)};
    
        std::vector<int64_t> data(size);
        std::generate(std::begin(data), std::end(data), random_generator);
    
        return data;
    }
    
    
    static std::filesystem::path CheckAndGetFileDescriptor(std::string file_name, bool exists)
    {
        auto file_path = std::filesystem::current_path() / file_name;
    
        if (exists && std::filesystem::exists(file_path)) {
            throw std::runtime_error{"Error! file exist"};
        }
    
        if (!exists && !std::filesystem::exists(file_path)) {
            throw std::runtime_error{"Error! file no exist"};
        }
    
        return file_path;
    }
    
    
    template<typename T>
    static void WriteDataToFile(std::vector<T> data, std::string file_name) 
    {
        std::ofstream out_stream(CheckAndGetFileDescriptor(file_name, true), std::ios::out);
    
        if (!out_stream.is_open()) {
            throw std::runtime_error{"Error open file"};
        }
    
        std::copy(std::begin(data), std::end(data), std::ostream_iterator<int64_t>{out_stream, " "});
    
        out_stream.close();
    }
    
    
    template<typename T, auto MaxOrMin>
    static T GetMaxOrMinValueFromFile(std::string file_name)
    {
        T ret{};
    
        if (MaxOrMin) {
            ret = std::numeric_limits<T>::min();
        } else {
            ret = std::numeric_limits<T>::max();
        }
    
        auto f_obj{ [&](T n){ MaxOrMin ? ret = std::max(ret, n) : ret = std::min(ret, n);} };
    
        std::ifstream in_stream(CheckAndGetFileDescriptor(file_name, false), std::ios::in);
    
        if (!in_stream.is_open()) {
            throw std::runtime_error{"Error open file"};
        }
    
        std::for_each(std::istream_iterator<T>(in_stream), std::istream_iterator<T>(), f_obj);   
    
        in_stream.close();
    
        return ret;
    }
    
    
    int main()
    {
        int64_t bottom{0};
        int64_t upper{30};
    
        uint64_t size{10};
    
        std::string file_name{"information"};
    
        auto data{GetVectorWithEntropy(size, bottom, upper)};
    
        try {
            WriteDataToFile<int64_t>(data, file_name);
    
            int64_t max_value{GetMaxOrMinValueFromFile<int64_t, true>(file_name)};
            int64_t min_value{GetMaxOrMinValueFromFile<int64_t, false>(file_name)};
    
            std::cout << "Maximum value : " << max_value << std::endl;
            std::cout << "Minimum value : " << min_value << std::endl;
            std::cout << "Sum : " << max_value + min_value << std::endl;
    
        } catch(std::exception& e) {
            std::cerr << e.what() << std::endl;
            return -1;
        }
    
        return 0;
    }
    
    • 0

相关问题

  • C++ 和循环依赖

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5