Профиль пользователя заблокирован сроком с 4 февраля 2022 г. и навсегда по причине: необходима проверка личности владельца аккаунта (в соответствии с п.2.6 условий пользовательского Соглашения)
Ответы пользователя по тегу C++
  • Увеличивать int несколько раз?

    edward_freedom
    @edward_freedom
    Вынеси обьявление переменной за цикл
    int q = 0;
    не подскажешь, как ограничить увеличение переменой? Чтоб она увеличивалась только на 1 единицу, не больше


    if(q != 1) {
        q++;
    }
    Ответ написан
  • Как сделать вырезание символов?

    edward_freedom
    @edward_freedom
    Используй вместоstr1[20]string

    string buffer;
    	vector<string> words;
    
    	cout << "Введите два предложения: " << endl;
    	while (words.size() <= 1 && getline(cin, buffer, '\n'))
    	{
    		words.push_back(buffer);
    	}
    
    	if (words[1].length() >= 4 && words[1].length() >= 4) {
    		words.push_back(string(words[0].substr(words[0].length() - 2, 2) + words[1].substr(0, 2)));
    	}
    
    	cout << endl << "Все предложения: " << endl;
    	for (auto word : words) {
    		std::cout << word << endl;;
    	}
    Ответ написан
    Комментировать
  • Массивы структур?

    edward_freedom
    @edward_freedom
    #include "stdafx.h"
    #include <iostream>
    #include "list"
    #include <algorithm>
    #include <sstream>
    #include <string>
    using namespace std;
    
    class Car {
    public:
    	enum Type
    	{
    		Passenger,
    		Cargo
    	};
    	int Price;
    	string Model;
    	Type TypeAuto;
    	
    
    	Car(int price, string model, Type type) {
    		this->Model = model;
    		this->Price = price;
    		this->TypeAuto = type;
    	}
    	string ToString() {
    
    		std::stringstream result;
    		result << "Model: " << this->Model <<
    			", Price: " << this->Price <<
    			", Type: " << this->TypeAuto;
    		return result.str();
    	}
    };
    
    class FilterCars {
    public:
    	list<Car> Cars;
    	int AveragePrice;
    	FilterCars(list<Car> cars, int averagePrice) {
    		this->Cars = cars;
    		this->AveragePrice = averagePrice;
    	}
    };
    
    void ShowCars(list<Car> cars) {
    	for (auto  car : cars) {
    		std::cout << car.ToString() << endl;;
    	}
    }
    
    FilterCars AveragePriceByType(list<Car> cars, Car::Type type) {
    	list<Car> selectCars;
    	std::copy_if(cars.begin(), cars.end(), std::back_inserter(selectCars), [type](Car car) {
    		return car.TypeAuto == type;
    	});
    	auto prices = 0;
    	for (auto car : selectCars) {
    		prices += car.Price;
    	}
    	auto average = prices / selectCars.size();
    	return FilterCars(selectCars, average);
    }
    
    
    
    int main()
    {
    	setlocale(LC_ALL, "russian");
    
    	auto cars = {
    		Car(40000, "Tesla", Car::Type::Passenger),
    		Car(34000, "Chevrolet", Car::Type::Passenger),
    		Car(324000, "Mercedes ", Car::Type::Passenger),
    		Car(114000, "Volvo ", Car::Type::Cargo),
    		Car(222000, "BMW ", Car::Type::Cargo),
    	};
    
    	
    
    	auto cargo = AveragePriceByType(cars, Car::Type::Cargo);
    	auto passenger = AveragePriceByType(cars, Car::Type::Passenger);
    	
    	cout << "Вывод грузовых автомобилей: " << endl;
    	ShowCars(cargo.Cars);
    	cout << "Средняя цена грузовых автомобилей: " << cargo.AveragePrice << endl << endl;
    
    	cout << "Вывод легковых автомобилей: " << endl;
    	ShowCars(passenger.Cars);
    	cout << "Средняя цена легковых автомобилей: " << passenger.AveragePrice << endl << endl;
    
    	system("pause");
    
    
        return 0;
    }
    Ответ написан
    7 комментариев
  • Компилятор выдает "�", почему?

    edward_freedom
    @edward_freedom
    Потому что, при выборе 1, у тебя условие попадает в int_, в любом другой последующем в char_, хоть ты 2, хоть 4 пиши, попадет в 5, потому что он последний. А все из за того, что ты правильно поставил break только на первое условие, а на остальных нет и всегда будет последнее условие.
    case 1:
    		chose = int_;
    		break;
    	case 2:
    		chose = double_;
    		break;
    	case 3:
    		chose = float_;
    		break;
    	case 4:
    		chose = long_;
    		break;
    	case 5:
    		chose = char_;
    		break;


    Твой код можно сократить с помощью шаблонов
    #include <iostream>
    #include <string> 
    using namespace std;
    enum Chose { int_, double_, float_, long_, char_ };
    
    
    template<typename Tn, typename Tp>
    Tn Power(Tn n, Tp p) {
    	Tn  result =  1;
    	for (int i = 0; i < p; i++)
    	{
    		result = result * n;
    	}
    	return result;
    }
    
    template<typename Tn, typename Tp>
    void UserInput() {
    	Tn  power =  1;
    	Tp  number =  1;
    	cout << "Введите число: ";
    	cin >> number;
    	cout << "Введите степень: ";
    	cin >> power;
    	Tn result = Power(number, power);
    	cout << "Result: " << result << endl;
    }
    
    
    int main()
    {
    	setlocale(LC_ALL, "russian");
    	Chose chose;
    	int chose_;
    	cout << "Выберите действие: ";
    	cin >> chose_;
    
    	switch (chose_)
    	{
    	case 1:
    		UserInput<int, int>();
    		break;
    	case 2:
    		UserInput<double, int>();
    		break;
    	case 3:
    		UserInput<int, float>();
    		break;
    	case 4:
    		UserInput<int, long>();
    		break;
    	case 5:
    		UserInput<double, char>();
    		break;
    	}
    
    	system("pause");
    }
    Ответ написан
    Комментировать
  • Символ собачка в строке?

    edward_freedom
    @edward_freedom
    std::string query = "SELECT * FROM users WHERE email='"+login+"' and password='"+md5(pass)+ "'";
    Ответ написан
    2 комментария
  • Можете помочь решить небольшую задачу на С++?

    edward_freedom
    @edward_freedom
    bool DigitOdd(int number) {
    	auto result = true;
    	while (number > 0)
    	{
    		int digit = number % 10;
    		number /= 10;
    		if (digit % 2 == 0) {
    			result = false;
    			break;
    		}
    	}
    	return result;
    }


    Не вырабатывай у себя привычку, переменные одной буквой называть, давай им нормальные имена
    Ответ написан
    2 комментария
  • Как получить доступ к элементам динамического массива по ссылке?

    edward_freedom
    @edward_freedom
    void Foo (Animal &arr)

    ты передаешь в аргументах не массив, а обьект
    class Animal {
    public:
    	std::string Name;
    };
    
    void Foo(Animal *arr) {
    	cout << arr[1].Name.c_str() << endl;
    }
    
    void main()
    {
    	Animal *animals = new Animal[3];
    
    	animals[0].Name = "Cat";
    	animals[1].Name = "Dog";
    	animals[2].Name = "Cow";
    
    
    	Foo(animals);
    
    	animals[1].Name = "Change to Dog";
    	Foo(animals);
    
    }
    Ответ написан
    Комментировать
  • Чем заменить printf_s("%.0lf", s) в C#?

    edward_freedom
    @edward_freedom
    https://docs.microsoft.com/en-us/dotnet/standard/b...

    Format specifier Name Description Examples
    "C" or "c" Currency Result: A currency value.

    Supported by: All numeric types.

    Precision specifier: Number of decimal digits.

    Default precision specifier: Defined by NumberFormatInfo.CurrencyDecimalDigits.

    More information: The Currency ("C") Format Specifier. 123.456 ("C", en-US) -> $123.46

    123.456 ("C", fr-FR) -> 123,46 €

    123.456 ("C", ja-JP) -> ¥123

    -123.456 ("C3", en-US) -> ($123.456)

    -123.456 ("C3", fr-FR) -> -123,456 €

    -123.456 ("C3", ja-JP) -> -¥123.456

    и тд
    Ответ написан
    Комментировать
  • С чем работать на C++ в Linux Mint?

    edward_freedom
    @edward_freedom
    Однозначно Qt. На нем написаны Телеграм, Стим, BattleNet
    Ответ написан
    Комментировать