• Почему программа на C++ не выводит результат?

    myjcom
    @myjcom Куратор тега C++
    scanf("%f", epsilon);
    scanf("%f", &epsilon);
    Но это только первая. дальше хуже.
    int res1 = 0;
      for(i = 0; i <= n; i++) {
        res1 = res1 * i;
    }

    int res1 = 0 
    ...
    res1 = 0 * i;
    
    float an = (3 * factorial())/X3factorial();

    деление на 0

    while (an > epsilon)
    ...

    когда условие станет false?

    int n = 1;
    float sum = 0;
    
    ...
    
    int n = n++; // ???


    Почему программа на C++ не выводит результат?

    начнем с того что это не С++ программа. в С++ это не должно компилироваться.
    Ответ написан
    3 комментария
  • Два одинаковых файла имеют разный размер в байтах?

    myjcom
    @myjcom Куратор тега C++
    BadCats,
    см. binary mode
    гарантируется что при записи двоичных данных в файл и последующем чтении двоичных данных из этого файла данные будут совпадать, равно как и при записи текстовых данных в файл и последующем чтении текстовых данных из этого файла.

    При записи текстовых данных в файл и последующей интерпретации их, при чтении, как двоичных, равно как и наоборот, ничего не гарантируется.

    Поэкспериментируй

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <cstring>
    #include <random>
    #include <iterator>
    #include <experimental/filesystem>
    using namespace std;
    namespace fs = experimental::filesystem;
    
    void fill_random(vector<char>& data)
    {
      std::random_device rd;
      std::mt19937 gen(rd());
      std::uniform_int_distribution<> dis(0, 255);
      generate(data.begin(), data.end(), [&]{ return dis(gen); });
    }
    
    int main()
    {
      vector<char> content(318);
    
      fill_random(content); // для чистоты эксперимента
    
      vector<char> content_copy;
    
      if(fs::exists("temp"))
      {
        cout << "delete temp dir\n";
        fs::remove_all("temp");
      }
    
      fs::create_directory("temp");
      cout << "create temp dir\n";
    
      if(auto file = ofstream("temp/file", ios_base::binary); file)
      {
        file.write(content.data(), content.size());
        cout << "write " << content.size() << " bytes\n";
      }
    
      if(fs::exists("temp/file"))
      {
        cout << "create copy..." << "\n";
        fs::copy_file("temp/file", "temp/file_copy");
      }
     
      if(fs::file_size("temp/file") == fs::file_size("temp/file_copy"))
      {
        auto file = ifstream("temp/file_copy", ios_base::binary);
        content_copy.resize(fs::file_size("temp/file_copy"));
        file.read(content_copy.data(), content_copy.size());
      }
    
      auto eq = memcmp(content.data(), content_copy.data(), content.size());
    
      if(eq == 0)
      {
        cout << "temp/file eq temp/file_copy\n"
             << "file size      == " << fs::file_size("temp/file") << "\n"
             << "file_copy size == " << fs::file_size("temp/file_copy") << endl;
      }
    
      if(auto text_file = ofstream("temp/text_file"); text_file)
      {
        copy(content.begin(), content.end(), ostream_iterator<char>(text_file));
      }
      
      if(fs::file_size("temp/file") == fs::file_size("temp/text_file"))
      {
        cout << "temp/file eq temp/text_file\n";
      }
      else
      {
        cout << "Surprise\n"
             << R"(fs::file_size("temp/file") == )" << fs::file_size("temp/file") << "\n"
             << R"(fs::file_size("temp/text_file") == )" << fs::file_size("temp/text_file") << endl;
      }
    
      cin.get();
    }


    P.S.
    Если ещё конкретнее

    Binary and text modes
    A text stream is an ordered sequence of characters composed into lines (zero or more characters plus a terminating '\n'). Whether the last line requires a terminating '\n' is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert \n to \r\n on output, and convert \r\n to \n on input)

    Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if all of the following is true:

    the data consist only of printing characters and the control characters \t and \n (in particular, on Windows OS, the character '\0x1A' terminates input)
    no \n is immediately preceded by a space character (space characters that are written out immediately before a \n may disappear when read)
    the last character is \n
    A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state.

    POSIX implementations do not distinguish between text and binary streams (there is no special mapping for \n or any other characters)
    Windows не POSIX.

    При чтении/записи данных в файл, текстовый редактор читает/пишет данные в "режиме текста" . Для записи/просмотра двоичных данных, нужен соответствующий просмоторщик/редактор.
    Ответ написан
    Комментировать
  • Почему указатель на char выводит всю строку, а не первый символ?

    myjcom
    @myjcom Куратор тега C++
    (для простоты опишем так)
    Внутри перегруженной версии
    operator<<

    https://code.woboq.org/gcc/libstdc++-v3/include/st...

    template<typename _CharT, typename _Traits>
        inline basic_ostream<_CharT, _Traits>&
        operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
        {
          if (!__s)
            __out.setstate(ios_base::badbit);
          else
            __ostream_insert(__out, __s,
                             static_cast<streamsize>(_Traits::length(__s)));
          return __out;
        }


    под капотом используется sputn

    Writes count characters to the output sequence from the character array whose first element is pointed to by s. The characters are written as if by repeated calls to sputc(). Writing stops when either count characters are written or a call to sputc() would have returned Traits::eof().

    где count это strlen(s);

    P.S.
    в C++ string literal это все таки const char*
    в С++ есть std::string который является предпочтительным в С++
    Ответ написан
    Комментировать
  • Почему printf не выводит переменные?

    myjcom
    @myjcom Куратор тега C++
    Почему printf не выводит переменные?

    printf("%s", "Znachenie", &p);
    int printf( const char* format, ... );

    выводит %s writes a character string которую вы передаете аргументом "Znachenie"
    %f converts floating-point number to the decimal notation которое вы передаете аргументом p
    printf("%s %f", "Znachenie", p);

    но так не совсем удобно
    вот так проще
    printf("Znachenie %f", p);

    оператор address-of перед именем переменной не нужен.
    Ответ написан
    Комментировать
  • Как применять модель "случайных блужданий без самопересечений" в java?

    myjcom
    @myjcom
    не могу найти ошибку

    Условие в while...
    int y = n/2;
    ... 
    && (y > (n-1))
    всегда false.
    т.к. (n / 2) <= (n - 1)

    Соответственно

    Программа в каждом случае выдаёт 0.

    int deadEnds = 0;
    ... 
    100*deadEnds/trials == 0
    0/n = 0

    https://rextester.com/CQOHTE74063
    Ответ написан
    Комментировать
  • Как решать задачу?

    myjcom
    @myjcom Куратор тега C++
    Собственно
    отсюда

    #include <algorithm>
    #include <iterator>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    auto fx = [](int x){
      int r = 0;
      switch(x % 3)
      {
        case 0:
          r = x * x;
          break;
        case 1:
          r = x;
          break;
        default:
          r = x / 3;
          break;
      }
      return r;
    };
    
    auto calculate = [](const vector<int>& vx, auto fx){
      vector<int> calcValues(vx.size());
      transform(vx.begin(), vx.end(), calcValues.begin(), fx);
      return calcValues;
    };
    
    int main()
    {
      cout << "Введи кол-во чисел: ";
      int n = 0;
      cin >> n;
    
      cout << "Введи через пробел " << n << " натуральных чисел:\n" << "$: ";
      vector<int> values(n);
      copy_n(istream_iterator<int>(cin), n, values.begin());
    
      cout << "Результат твоих расчетов:\n";
      copy_n(calculate(values, fx).begin(), n, ostream_iterator<int>(cout, "\n"));
    }


    тебе нужна только fx в остальное можешь не погружаться, кроме того что
    Даны натуральные числа

    https://ru.wikipedia.org/wiki/Натуральное_число --> unsigned
    Ответ написан
    Комментировать
  • Не могу найти ошибку в коде java core, спасибо?

    myjcom
    @myjcom
    Извините за сленг RTFM
    https://www.internet-technologies.ru/articles/srav...
    Оператор == проверяет ссылки, а не значения

    В Java сравнение строк equals проверяет исходное содержимое строки. Он возвращает true, если параметр — это объект String, который представляет собой ту же строку символов, что и объект...
    Ответ написан
    Комментировать
  • Как посчитать количество пара в set?

    myjcom
    @myjcom Куратор тега C++
    Попробую угадать.
    Если нужно считать это значит что может быть больше одного.
    Если больше одного в данном случае (set) то это multiset.
    Вы же count используете не для проверки наличия элемента во множестве?
    #include <iostream>
    #include <set>
    #include <utility>
    #include <string>
    using namespace std;
    
    int main()
    {
      multiset<pair<string, string>> pss{
        {"one", "one"}, {"two", "two"}, {"two", "two"},
        {"three", "three"}, {"three", "three"}, {"three", "three"}
      };
    
      auto cnt = pss.count({"three", "three"});
    
      cout << R"(pss.count({"three", "three"}))" << " == " << cnt << endl;
    }
    Ответ написан
    Комментировать
  • Как считать вторую строку?

    myjcom
    @myjcom Куратор тега C++
    Но не таким способом

    #include <iostream>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    #include <vector>
    using namespace std;
    
    int main()
    {
      size_t n = 4;
      string s = "42 54 35 76";
      
      istringstream is(s);
      
      vector<int> v;
      copy_n(istream_iterator<int>(is), n, back_inserter(v));
    
      /*******
      ** vector<int> v2(n);
      ** copy_n(istream_iterator<int>(is), n, v.begin());
      *******/
      copy_n(v.begin(), n, ostream_iterator<int>(cout, " "));
    }

    Ответ написан
    Комментировать
  • Цикл с EOF в С?

    myjcom
    @myjcom
    выводится количество символов умноженное на два?

    пробелы, символы перевода строки и т.д. и т.п. это тоже символы вот так и получается попробуйте так
    12345678
    Ответ написан
    Комментировать
  • Как передать текст через командную строку в Си?

    myjcom
    @myjcom
    https://en.cppreference.com/w/c/language/main_function
    #include<stdio.h>
    int main(int argc, char* argv[])
    {
      if(argc > 0)
      {
        for(int i = 0; i != argc; ++i)
           printf("%s\n", argv[i]);
      }
    }

    argv[0] = имя программы, далее по порядку аргументы 1, 2, 3 ... , argc --> argv[1], argv[2], ... , argv[argc]
    Ответ написан
    1 комментарий
  • Как сохранить в памяти и суммировать в число определенную в байтах массу файлов а затем использовать результат?

    myjcom
    @myjcom Куратор тега C++
    https://en.cppreference.com/w/cpp/filesystem
    Если доступен С++17
    #include<iostream>
    #include<filesystem>
    #include<string>
    using namespace std;
    namespace fs = filesystem;
    
    auto getDirectorySize(const fs::path& p)
    {
      uintmax_t size = 0;
      if(fs::is_directory(p))
      {
        for(const auto& f : fs::directory_iterator(p))
        {
          size += f.file_size();
        }
      }
      return size;
    }
    
    int main()
    {
      string directory{ "C:\\TEMP" };
      fs::path dp{ directory };
      
      auto size{ getDirectorySize(dp) };
      cout << "size of "  << directory 
           << " "         << size 
           << " bytes"    << endl;
    }

    Или

    #include<iostream>
    #include<fstream>
    #include<string>
    #include<vector>
    using namespace std;
    
    size_t getFileSize(const string& filename)
    {
      ifstream ifs(filename);
      size_t size = 0;
      if(ifs)
      {
        ifs.seekg(0, ios_base::end);
        size = ifs.tellg();
      }
      return size;
    }
    
    int main()
    {
      vector<string> filenames{
        "C:\\TEMP\\aaa.txt", "C:\\TEMP\\bbb.txt", "C:\\TEMP\\ccc.txt"
      };
    
      size_t size = 0;
    
      for(const string& fn : filenames)
      {
        size += getFileSize(fn);
      }
    
      cout << "Size: " << size << endl;
    }

    Ответ написан
    7 комментариев
  • Как в Arduino развернуть данные?

    myjcom
    @myjcom Куратор тега C++
    развернуть

    Как-то так

    // LEFT --> [127 ... 0] --> [32 ... 4095]
    // 
    // RIGHT --> [129 ... 255] --> [32 ... 4095]
    
    int calc_speed(int value)
    {
      int speed = 0; // для наглядности без ? :
      if(value > 128)
      {
        speed = 4095 / 127 * (value - 128);
      }
      else
      {
        speed = 4095 / 127 * (128 - value);
      }
      return speed;
    }
    
    void drive_forward(int speed)
    {
      MSS.analogWrite(15, 0);
      MSS.analogWrite(14, speed);                                
    }
    
    void drive_backward(int speed)
    {
      MSS.analogWrite(14, 0);                             
      MSS.analogWrite(15, speed);
    }
    
    void stop()
    {
      MSS.analogWrite(14, 0);                             
      MSS.analogWrite(15, 0);
    }
    
    void move()
    {
      int ds = ps2x.Analog(PSS_LX);
      
      if(ds > 128)
      {
        drive_forward(calc_speed(ds));
      }
      else if(ds < 128)
      {
        drive_backward(calc_speed(ds));
      }
      else
      {
        stop();
      }
    }
    Ответ написан
    Комментировать
  • Stl c++ min elem?

    myjcom
    @myjcom Куратор тега C++
    гуглил, что-то не выходит понять

    https://en.cppreference.com/w/cpp/algorithm/min_element

    но почему она не возвращает значения сразу , а только в конце? каким образом происходит сравнение?

    min_element
    template<class ForwardIt, class Compare>
    ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp)
    {
        if (first == last) return last;
     
        ForwardIt smallest = first;
        ++first;
        for (; first != last; ++first) { // не возвращает значения сразу
            if (comp(*first, *smallest)) { //  каким образом происходит сравнение
                smallest = first;
            }
        }
        return smallest; // а только в конце
    }


    написал код чтобы легче было ориентироваться

    https://ru.cppreference.com/w/cpp/numeric/math/abs
    #include<cmath>
    // ...
    
    int result = *min_element(array.begin(), array.end(), [](int a, int b) { return abs(a) < abs(b); });
    
    // ...
    Ответ написан
    Комментировать
  • Проверка на числовой ввод. Как работает код?

    myjcom
    @myjcom Куратор тега C++
    while (!(cin >> x) or cin.get() != '\n')
    пока( не (прочитать из буфера ввода целое) или прочитанный из буфера символ не равен '\n')

    не понимаю как работает второй while.

    while (cin.get() != '\n');
    так же.
    пока(прочитанный из буфера символ не равен '\n') nop


    Так получше будет
    string s;
    getline(cin, s);
    istringstream is(s);
    while(is >> s)
    {
      int i = 0;
      try
      {
        i = stoi(s);
      }
      catch(exception& e)
      {
        cout << "Ошибка: " << e.what() << " " << s << "\n";
        continue;
      }
      cout << "i == " << i << "\n";
    }
    Ответ написан
    4 комментария
  • Как считывать построчно данные из буфера?

    myjcom
    @myjcom Куратор тега C++
    string msg = "Съешь ещё этих мягких французских булок";
      ostringstream os;
      os << "Съешь ещё этих мягких французских булок\n"
         << "Съешь ещё этих мягких французских булок\n"
         << "Съешь ещё этих м"
         << "ягких французских булок\n"
         << "Съешь ещё этих мягких французских булок\n";
    
      istringstream is(os.str());
    
      string line;
     
      while(is)
      {
        getline(is, line);
        if(is.fail())
        {
          os.str("");
          os << line;
          break;
        }
        cout << "line: " << line << "\n";
      }
    Ответ написан
  • Как найти у, заданную параметрически?

    myjcom
    @myjcom Куратор тега C++
    "приравниваю" - это очень плохая терминология.
    Есть объявление и инициализация, есть присвоение. Что такое обнулил/занулил/приравнял непонятно.

    init-declarator-list - comma-separated list of declarators with optional initializers. запятая разделитель.

    comma operator a, b - evaluate expression a, disregard its return value and complete any side-effects, then evaluate expression b, returning the type and the result of this evaluation запятая оператор.

    запятая в объявлении переменных несет только синтаксическую функцию разделителя.

    перед компиляцией это
    float i, a, x = 0;
    будет развернуто в это
    float i;
    float a;
    float x = 0;


    Подскажите пожалуйста, где я ошибаюсь..

    даже если предположить что i == 0.0 и a == 0.0
    float y = ((i + x) / (2.5 * i + pow(x, i)) ) + a * pow(sin(x), i + 1);

    что получается?
    float y = x / 1;

    это бессмысленно, предположу учитывая параметрическое задание ф-ции и график, что тут должен быть цикл.
    Ответ написан
    Комментировать
  • Почему ArrayList итерируется быстрее, чем LinkedList?

    myjcom
    @myjcom
    С чем это связано?

    ArrayList это массив вставка и доступ O(1)
    LinkedList это связный список вставка и доступ O(n)

    В вашем случае (суммирование) полный перебор это в любом случае O(n)
    Значит все дело в вставке, чтобы вставить элемент в конец списка нужно добраться до конечного элемента. Каждый раз когда вы вставляете новый элемент, вы перебираете список от начала до конца, что в свою очередь в вашем цикле дает O(n log n n ^ 2)

    Хотя если следовать тому что написано в документации, LinkedList add эквивалентно addLast
    тогда все немного иначе, тормоза появляются из-за большого количества выделений памяти (это дорогостоящая операция)
    Потому как в ArrayList она
    выделяется с запасом

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

    , а в LinkedList каждый раз при добавлении нового элемента.

    UPD:
    Вот так итерируется LinkedList

    собственно обычный обход списка src
    public ListIterator<E> listIterator(int index) {
      checkPositionIndex(index);
      return new ListItr(index);
    }
    // ...
    private class ListItr implements ListIterator<E> {
      private Node<E> lastReturned = null;
      private Node<E> next;
      private int nextIndex;
      private int expectedModCount = modCount;
      ListItr(int index) {
        // assert isPositionIndex(index);
        next = (index == size) ? null : node(index);
        nextIndex = index;
      }
      public boolean hasNext() {
        return nextIndex < size;
      }
      public E next() {
        checkForComodification();
        if (!hasNext())
          throw new NoSuchElementException();
        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.item;
    }


    А так ArrayList

    hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/sha...
    private class Itr implements Iterator<E> {
      int cursor;       // index of next element to return
      int lastRet = -1; // index of last element returned; -1 if no such
      int expectedModCount = modCount;
      public boolean hasNext() {
        return cursor != size;
      }
      @SuppressWarnings("unchecked")
      public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
          throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
          throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    Ответ написан
    6 комментариев
  • Как на C++ дергать логи из syslog?

    myjcom
    @myjcom Куратор тега C++
    Oct  2 23:39:48 dvrh systemd-resolved[562]: Server returned er....

    для такого вида примитив.
    только по времени.

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sys/utsname.h>
    
    std::string getTimestamp(const std::string& line)
    {
      auto pos = line.rfind(' ');
      return line.substr(pos + 1, line.size() - pos);
    }
    
    int main(int argc, char* argv[])
    {
      if(argc < 3)
      {
        std::cerr << "usage: file timestamp timestamp\n/var/log/syslog 11:00:00 12:00:00\n";
        exit(EXIT_FAILURE);
      }
    
      struct utsname uts;
    
      if(uname(&uts) == -1)
      {
        exit(EXIT_FAILURE);
      }
    
      if(std::ifstream flog(argv[1]); flog)
      {
        std::string start{argv[2]};
        std::string stop {argv[3]};
        std::string line;
    
        while(getline(flog, line))
        {
          std::string header = getTimestamp(line.substr(0, line.find(uts.nodename) - 1));
          if(header >= start && header <= stop)
          {
            std::cout << line << "\n";
          }
        }
      }
      else
      {
        std::cerr << "Cannot open file: " << argv[1];
      }
    }


    если еще и с датой - чуть больше.
    Ответ написан
    Комментировать