Гид по технологиям

Простые и сложные проценты — расчёт на C++, Python и JavaScript

• 3 min read • Программирование • Обновлено 20 Nov 2025
Простые и сложные проценты — примеры на C++, Python, JS
Простые и сложные проценты — примеры на C++, Python, JS

Мужчина, держащий калькулятор и считающий проценты

Математика часто встречается в коде. Даже простые финансовые формулы полезно уметь реализовывать. Ниже — понятные определения, формулы и рабочие примеры реализации простых и сложных процентов на трёх языках.

Как вычислить простые проценты?

Простые проценты — это метод начисления процентов только на основную (принципальную) сумму. Формула:

Simple Interest = (P × R × T) / 100
Где:
P = Principal (основная сумма)
R = Rate (годовая ставка в процентах)
T = Time (в годах)

Краткое пояснение: если ставка задана в годах, а период меньше или больше года — приведите время к годам (например, 6 месяцев = 0.5 года).

Условие задачи

Даны основная сумма, годовая ставка и время. Нужно посчитать и вывести простые проценты. Пример: P=1000, R=7, T=2 → SI = (1000×7×2)/100 = 140.

C++: вычисление простых процентов

// C++ program to calculate simple interest
// for given principal amount, time, and rate of interest.

#include 
using namespace std;

// Function to calculate simple interest
float calculateSimpleInterest(float principal, float rate, float timePeriod)
{
    return (principal * rate * timePeriod) / 100;
}

int main()
{
    float principal1 = 1000;
    float rate1 = 7;
    float timePeriod1 = 2;
    cout << "Test case: 1" << endl;
    cout << "Principle amount: " << principal1 << endl;
    cout << "Rate of interest: " << rate1 << endl;
    cout << "Time period: " << timePeriod1 << endl;
    cout << "Simple Interest: " << calculateSimpleInterest(principal1, rate1, timePeriod1) << endl;

    float principal2 = 5000;
    float rate2 = 5;
    float timePeriod2 = 1;
    cout << "Test case: 2" << endl;
    cout << "Principle amount: " << principal2 << endl;
    cout << "Rate of interest: " << rate2 << endl;
    cout << "Time period: " << timePeriod2 << endl;
    cout << "Simple Interest: " << calculateSimpleInterest(principal2, rate2, timePeriod2) << endl;

    float principal3 = 5800;
    float rate3 = 4;
    float timePeriod3 = 6;
    cout << "Test case: 3" << endl;
    cout << "Principle amount: " << principal3 << endl;
    cout << "Rate of interest: " << rate3 << endl;
    cout << "Time period: " << timePeriod3 << endl;
    cout << "Simple Interest: " << calculateSimpleInterest(principal3, rate3, timePeriod3) << endl;

    return 0;
}

Вывод (пример):

Test case: 1
Principle amount: 1000
Rate of interest: 7
Time period: 2
Simple Interest: 140
Test case: 2
Principle amount: 5000
Rate of interest: 5
Time period: 1
Simple Interest: 250
Test case: 3
Principle amount: 5800
Rate of interest: 4
Time period: 6
Simple Interest: 1392

Python: вычисление простых процентов

# Python program to calculate simple interest
# for given principal amount, time, and rate of interest.

# Function to calculate simple interest
def calculateSimpleInterest(principal, rate, timePeriod):
    return (principal * rate * timePeriod) / 100

principal1 = 1000
rate1 = 7
timePeriod1 = 2
print("Test case: 1")
print("Principle amount:", principal1)
print("Rate of interest:", rate1)
print("Time period:", timePeriod1)
print("Simple Interest:", calculateSimpleInterest(principal1, rate1, timePeriod1))

principal2 = 5000
rate2 = 5
timePeriod2 = 1
print("Test case: 2")
print("Principle amount:", principal2)
print("Rate of interest:", rate2)
print("Time period:", timePeriod2)
print("Simple Interest:", calculateSimpleInterest(principal2, rate2, timePeriod2))

principal3 = 5800
rate3 = 4
timePeriod3 = 6
print("Test case: 3")
print("Principle amount:", principal3)
print("Rate of interest:", rate3)
print("Time period:", timePeriod3)
print("Simple Interest:", calculateSimpleInterest(principal3, rate3, timePeriod3))

Вывод (пример):

Test case: 1
Principle amount: 1000
Rate of interest: 7
Time period: 2
Simple Interest: 140.0
Test case: 2
Principle amount: 5000
Rate of interest: 5
Time period: 1
Simple Interest: 250.0
Test case: 3
Principle amount: 5800
Rate of interest: 4
Time period: 6
Simple Interest: 1392.0

JavaScript: вычисление простых процентов

// JavaScript program to calculate simple interest
// for given principal amount, time, and rate of interest.

// Function to calculate simple interest
function calculateSimpleInterest(principal, rate, timePeriod) {
  return (principal * rate * timePeriod) / 100;
}

var principal1 = 1000;
var rate1 = 7;
var timePeriod1 = 2;
document.write("Test case: 1" + "\n");
document.write("Principle amount: " + principal1 + "\n");
document.write("Rate of interest: " + rate1 + "\n");
document.write("Time period: " + timePeriod1 + "\n");
document.write("Simple Interest: " + calculateSimpleInterest(principal1, rate1, timePeriod1) + "\n");

var principal2 = 5000;
var rate2 = 5;
var timePeriod2 = 1;
document.write("Test case: 2" + "\n");
document.write("Principle amount: " + principal2 + "\n");
document.write("Rate of interest: " + rate2 + "\n");
document.write("Time period: " + timePeriod2 + "\n");
document.write("Simple Interest: " + calculateSimpleInterest(principal2, rate2, timePeriod2) + "\n");

var principal3 = 5800;
var rate3 = 4;
var timePeriod3 = 6;
document.write("Test case: 3" + "\n");
document.write("Principle amount: " + principal3 + "\n");
document.write("Rate of interest: " + rate3 + "\n");
document.write("Time period: " + timePeriod3 + "\n");
document.write("Simple Interest: " + calculateSimpleInterest(principal3, rate3, timePeriod3) + "\n");

Вывод (пример):

Test case: 1
Principle amount: 1000
Rate of interest: 7
Time period: 2
Simple Interest: 140
Test case: 2
Principle amount: 5000
Rate of interest: 5
Time period: 1
Simple Interest: 250
Test case: 3
Principle amount: 5800
Rate of interest: 4
Time period: 6
Simple Interest: 1392

Важно: простые проценты не учитывают реинвестирование. Для доходов, где проценты начисляются на накопленный остаток, используйте сложные проценты.

Как вычислить сложные проценты

Сложные проценты — это начисление процентов на уже начисленные проценты. Формулы:

Amount = P × (1 + R/100)^T
Compound Interest = Amount - P
Где:
P = Principal (основная сумма)
R = Rate (годовая ставка в процентах)
T = Time (в годах)

Пример: P=1000, R=7, T=2 → Amount = 1000×(1+0.07)^2 ≈ 1144.9 → CI ≈ 144.9.

Условие задачи

Даны основная сумма, годовая ставка и время. Нужно посчитать и вывести сложные проценты.

C++: вычисление сложных процентов

// C++ program to calculate compound interest
// for given principal amount, time, and rate of interest.

#include 
using namespace std;

// Function to calculate compound interest
float calculateCompoundInterest(float principal, float rate, float timePeriod)
{
    double amount = principal * (pow((1 + rate / 100), timePeriod));
    return amount - principal;
}

int main()
{
    float principal1 = 1000;
    float rate1 = 7;
    float timePeriod1 = 2;
    cout << "Test case: 1" << endl;
    cout << "Principle amount: " << principal1 << endl;
    cout << "Rate of interest: " << rate1 << endl;
    cout << "Time period: " << timePeriod1 << endl;
    cout << "Compound Interest: " << calculateCompoundInterest(principal1, rate1, timePeriod1) << endl;

    float principal2 = 5000;
    float rate2 = 5;
    float timePeriod2 = 1;
    cout << "Test case: 2" << endl;
    cout << "Principle amount: " << principal2 << endl;
    cout << "Rate of interest: " << rate2 << endl;
    cout << "Time period: " << timePeriod2 << endl;
    cout << "Compound Interest: " << calculateCompoundInterest(principal2, rate2, timePeriod2) << endl;

    float principal3 = 5800;
    float rate3 = 4;
    float timePeriod3 = 6;
    cout << "Test case: 3" << endl;
    cout << "Principle amount: " << principal3 << endl;
    cout << "Rate of interest: " << rate3 << endl;
    cout << "Time period: " << timePeriod3 << endl;
    cout << "Compound Interest: " << calculateCompoundInterest(principal3, rate3, timePeriod3) << endl;

    return 0;
}

Вывод (пример):

Test case: 1
Principle amount: 1000
Rate of interest: 7
Time period: 2
Compound Interest: 144.9
Test case: 2
Principle amount: 5000
Rate of interest: 5
Time period: 1
Compound Interest: 250
Test case: 3
Principle amount: 5800
Rate of interest: 4
Time period: 6
Compound Interest: 1538.85

Python: вычисление сложных процентов

# Python program to calculate compound interest
# for given principal amount, time, and rate of interest.

# Function to calculate compound interest
def calculateCompoundInterest(principal, rate, timePeriod):
    amount = principal * (pow((1 + rate / 100), timePeriod))
    return amount - principal

principal1 = 1000
rate1 = 7
timePeriod1 = 2
print("Test case: 1")
print("Principle amount:", principal1)
print("Rate of interest:", rate1)
print("Time period:", timePeriod1)
print("Compound Interest:", calculateCompoundInterest(principal1, rate1, timePeriod1))

principal2 = 5000
rate2 = 5
timePeriod2 = 1
print("Test case: 2")
print("Principle amount:", principal2)
print("Rate of interest:", rate2)
print("Time period:", timePeriod2)
print("Compound Interest:", calculateCompoundInterest(principal2, rate2, timePeriod2))

principal3 = 5800
rate3 = 4
timePeriod3 = 6
print("Test case: 3")
print("Principle amount:", principal3)
print("Rate of interest:", rate3)
print("Time period:", timePeriod3)
print("Compound Interest:", calculateCompoundInterest(principal3, rate3, timePeriod3))

Вывод (пример):

Test case: 1
Principle amount: 1000
Rate of interest: 7
Time period: 2
Compound Interest: 144.9000000000001
Test case: 2
Principle amount: 5000
Rate of interest: 5
Time period: 1
Compound Interest: 250.0
Test case: 3
Principle amount: 5800
Rate of interest: 4
Time period: 6
Compound Interest: 1538.8503072768026

JavaScript: вычисление сложных процентов

// JavaScript program to calculate compound interest
// for given principal amount, time, and rate of interest.

// Function to calculate compound interest
function calculateCompoundInterest(principal, rate, timePeriod) {
  var amount = principal * (Math.pow((1 + rate / 100), timePeriod));
  return amount - principal;
}

var principal1 = 1000;
var rate1 = 7;
var timePeriod1 = 2;
document.write("Test case: 1" + "\n");
document.write("Principle amount: " + principal1 + "\n");
document.write("Rate of interest: " + rate1 + "\n");
document.write("Time period: " + timePeriod1 + "\n");
document.write("Compound Interest: " + calculateCompoundInterest(principal1, rate1, timePeriod1) + "\n");

var principal2 = 5000;
var rate2 = 5;
var timePeriod2 = 1;
document.write("Test case: 2" + "\n");
document.write("Principle amount: " + principal2 + "\n");
document.write("Rate of interest: " + rate2 + "\n");
document.write("Time period: " + timePeriod2 + "\n");
document.write("Compound Interest: " + calculateCompoundInterest(principal2, rate2, timePeriod2) + "\n");

var principal3 = 5800;
var rate3 = 4;
var timePeriod3 = 6;
document.write("Test case: 3" + "\n");
document.write("Principle amount: " + principal3 + "\n");
document.write("Rate of interest: " + rate3 + "\n");
document.write("Time period: " + timePeriod3 + "\n");
document.write("Compound Interest: " + calculateCompoundInterest(principal3, rate3, timePeriod3) + "\n");

Вывод (пример):

Test case: 1
Principle amount: 1000
Rate of interest: 7
Time period: 2
Compound Interest: 144.9000000000001
Test case: 2
Principle amount: 5000
Rate of interest: 5
Time period: 1
Compound Interest: 250
Test case: 3
Principle amount: 5800
Rate of interest: 4
Time period: 6
Compound Interest: 1538.8503072768008

Шпаргалка и руководство по выбору

АтрибутПростые процентыСложные проценты
Формула(P×R×T)/100P×(1+R/100)^T − P
Когда применятьКраткосрочные займы или фиксированные начисленияИнвестиции, депозиты, реинвестирование
Рост со временемЛинейныйЭкспоненциальный

Мини-методология для внедрения в проект:

  1. Решите, привязана ли ставка к году. Приводите время к годам.
  2. Реализуйте чистые функции calculateSimpleInterest и calculateCompoundInterest.
  3. Добавьте юнит-тесты на граничные случаи (нулевая сумма, нулевая ставка, нулевое время).
  4. Документируйте ожидаемый формат входных данных и выходных (float/decimal).

Критерии приёмки:

  • Функция возвращает 0 при P=0 или T=0.
  • Для простых процентов повторение периода N раз даёт N-кратный рост линейно.
  • Для сложных процентов проверка на равенство с ручным расчётом (с погрешностью для float).

Роль-based чек-листы:

  • Новичок: проверить корректность формул на известных примерах.
  • Разработчик: покрыть юнит-тестами, учесть типы данных и погрешности плавающей точки.
  • QA: протестировать граничные значения и отрицательные/ненормативные входы.

1-line глоссарий:

  • Principal: первоначальная сумма денег.
  • Rate: годовая процентная ставка в процентах.
  • Time: период в годах.

Когда простой подход не годится

  • Если проценты начисляют чаще, чем раз в год (ежемесячно, ежеквартально), используйте формулу с компаундированием по периодам: A=P(1+R/n)^(nT), где n — число начислений в году.
  • Для финансовых приложений с высокой точностью выбирайте decimal-тип или библиотеку для фиксированной точности, чтобы избежать ошибок IEEE float.

Краткое резюме

  • Простые проценты подходят для простых случаев и коротких периодов.
  • Сложные проценты учитывают реинвестирование и дают больший итог при длительном хранении.
  • Примеры на C++, Python и JavaScript показывают реализацию и тестовые случаи.

Спасибо за чтение. Начните с простых функций и постепенно добавьте проверки и тесты для надёжности.

Поделиться: X/Twitter Facebook LinkedIn Telegram
Автор
Редакция

Похожие материалы

Несколько аккаунтов Skype: Multi Skype Launcher
Программное обеспечение

Несколько аккаунтов Skype: Multi Skype Launcher

Журнал для работы: повысить продуктивность
Productivity

Журнал для работы: повысить продуктивность

Персональные звуки уведомлений на Android
Android.

Персональные звуки уведомлений на Android

Скачивание шоу Hulu для офлайн‑просмотра
Стриминг

Скачивание шоу Hulu для офлайн‑просмотра

Microsoft Start: персонализированная новостная лента
Новости

Microsoft Start: персонализированная новостная лента

Как изменить имя в Epic Games быстро
Гайды

Как изменить имя в Epic Games быстро