Помогите написать программу в с++ - Вопросы по С+

Вопрос Помогите написать программу в с++

Регистрация
16 Окт 2013
Сообщения
76
Репутация
0
Спасибо
0
Монет
0
Напиши програм для c++

Напишите программу, которая запрашивает у пользователя положительное целое число n. Программа должна вывести сумму первых n элементов последовательности: 2 - 4 + 6 - 8 + 10 - 12 ...
 
Регистрация
22 Ноя 2013
Сообщения
96
Репутация
0
Спасибо
0
Монет
0
#include <iostream>

int main() {
int n;
std::cout << "Введите положительное целое число n: ";
std::cin >> n;

int sum = 0;
int sign = 1;

for (int i = 1; i <= n; ++i) {
sum += sign * 2 * i;
sign *= -1; // Меняем знак на противоположный
}

std::cout << "Сумма первых " << n << " элементов последовательности: " << sum << std::endl;

return 0;
}
 
Регистрация
7 Дек 2013
Сообщения
83
Репутация
0
Спасибо
0
Монет
0
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

class SumAlternatingSeries {
public:
SumAlternatingSeries() : ordinal_term(0) {}
private:
unsigned long long ordinal_term;
void check_value_type(string& str) {
if (str.empty()) {
str = "0";
return;
}
if (str.front() < 0 || !isdigit(str.front())) {
str = "0";
return;
}
while (str.front() == '0') {
if (str.length() == 1 && str.front() == '0') {
return;
}
str = str.erase(0, 1);
}
for (auto ch : str) {
if (ch < 0 || !isdigit(ch)) {
str = "0";
return;
}
}
}
friend istream& operator>>(istream& inp, SumAlternatingSeries& sas) {
string tmp;
getline(inp, tmp);
sas.check_value_type(tmp);
sas.ordinal_term = stoull(tmp);
return inp;
}
friend ostream& operator<<(ostream& out, const SumAlternatingSeries& sas) {
const auto ot = sas.ordinal_term;
if (!ot) {
return out << "Erroneous data!";
}
auto result = ot & 1 ? ot + 1 : ot;
if (~ot & 1) {
out.put('-');
}
return out << result;
}
};

int main() {
SumAlternatingSeries sas;
while (true) {
cout << ">>> ";
cin >> sas;
cout << "<<< ";
cout << sas << '\n';
}
}
 
Сверху Снизу