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

Простые и сложные проценты: формулы и примеры на Python, C++ и JavaScript

4 min read Финансы Обновлено 03 Jan 2026
Простые и сложные проценты — примеры на Python, C++, JS
Простые и сложные проценты — примеры на Python, C++, JS

Мужчина с калькулятором в руках

Кратко о терминах

  • Принципал (P): первоначальная сумма денег.
  • Ставка (R): процентная ставка в год (в процентах).
  • Время (T): период времени (обычно в годах).

Важно: слова “principle” в исходных примерах содержат орфографическую ошибку. В финансах правильно “principal” — принципал, первоначальная сумма.

Как рассчитать простой процент

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

Simple Interest = (P x R x T)/100   
Where,   
P = Principle Amount  
R = Rate  
T = Time

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

Даны принципал, процентная ставка и время. Нужно вычислить и вывести простой процент. Пример: P = 1000, R = 7, T = 2 → Simple Interest = 140.

Программа на C++ для расчёта простого процента

// C++ program to calculate simple interest  
// for given principle amount, time, and rate of interest.  
  
#include   
using namespace std;  
  
// Function to calculate simple interest  
float calculateSimpleInterest(float principle, float rate, float timePeriod)  
{  
 return (principle * rate * timePeriod) / 100;  
}  
  
  
int main()  
{  
 float principle1 = 1000;  
 float rate1 = 7;  
 float timePeriod1 = 2;  
 cout << "Test case: 1" << endl;  
 cout << "Principle amount: " << principle1 << endl;  
 cout << "Rate of interest: " << rate1 << endl;  
 cout << "Time period: " << timePeriod1 << endl;  
 cout << "Simple Interest: " << calculateSimpleInterest(principle1, rate1, timePeriod1) << endl;  
  
 float principle2 = 5000;  
 float rate2 = 5;  
 float timePeriod2 = 1;  
 cout << "Test case: 2" << endl;  
 cout << "Principle amount: " << principle2 << endl;  
 cout << "Rate of interest: " << rate2 << endl;  
 cout << "Time period: " << timePeriod2 << endl;  
 cout << "Simple Interest: " << calculateSimpleInterest(principle2, rate2, timePeriod2) << endl;  
  
 float principle3 = 5800;  
 float rate3 = 4;  
 float timePeriod3 = 6;  
 cout << "Test case: 3" << endl;  
 cout << "Principle amount: " << principle3 << endl;  
 cout << "Rate of interest: " << rate3 << endl;  
 cout << "Time period: " << timePeriod3 << endl;  
 cout << "Simple Interest: " << calculateSimpleInterest(principle3, 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

Связанные темы: поиск делителей натурального числа в C++, Python и JavaScript.

Программа на Python для расчёта простого процента

# Python program to calculate simple interest  
# for given principle amount, time, and rate of interest.  
  
# Function to calculate simple interest  
def calculateSimpleInterest(principle, rate, timePeriod):  
    return (principle * rate * timePeriod) / 100  
  
  
principle1 = 1000  
rate1 = 7  
timePeriod1 = 2  
print("Test case: 1")  
print("Principle amount:", principle1)  
print("Rate of interest:", rate1)  
print("Time period:", timePeriod1)  
print("Simple Interest:", calculateSimpleInterest(principle1, rate1, timePeriod1))  
  
principle2 = 5000  
rate2 = 5  
timePeriod2 = 1  
print("Test case: 2")  
print("Principle amount:", principle2)  
print("Rate of interest:", rate2)  
print("Time period:", timePeriod2)  
print("Simple Interest:", calculateSimpleInterest(principle2, rate2, timePeriod2))  
  
principle3 = 5800  
rate3 = 4  
timePeriod3 = 6  
print("Test case: 3")  
print("Principle amount:", principle3)  
print("Rate of interest:", rate3)  
print("Time period:", timePeriod3)  
print("Simple Interest:", calculateSimpleInterest(principle3, 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

Связанные темы: выполнение задачи FizzBuzz на разных языках.

Программа на JavaScript для расчёта простого процента

// JavaScript program to calculate simple interest  
// for given principle amount, time, and rate of interest.  
  
// Function to calculate simple interest  
function calculateSimpleInterest(principle, rate, timePeriod) {  
 return (principle * rate * timePeriod) / 100;  
}  
  
var principle1 = 1000;  
var rate1 = 7;  
var timePeriod1 = 2;  
document.write("Test case: 1" + "  \n");  
document.write("Principle amount: " + principle1 + "  \n");  
document.write("Rate of interest: " + rate1 + "  \n");  
document.write("Time period: " + timePeriod1 + "  \n");  
document.write("Simple Interest: " + calculateSimpleInterest(principle1, rate1, timePeriod1) + "  \n");  
  
var principle2 = 5000;  
var rate2 = 5;  
var timePeriod2 = 1;  
document.write("Test case: 2" + "  \n");  
document.write("Principle amount: " + principle2 + "  \n");  
document.write("Rate of interest: " + rate2 + "  \n");  
document.write("Time period: " + timePeriod2 + "  \n");  
document.write("Simple Interest: " + calculateSimpleInterest(principle2, rate2, timePeriod2) + "  \n");  
  
var principle3 = 5800;  
var rate3 = 4;  
var timePeriod3 = 6;  
document.write("Test case: 3" + "  \n");  
document.write("Principle amount: " + principle3 + "  \n");  
document.write("Rate of interest: " + rate3 + "  \n");  
document.write("Time period: " + timePeriod3 + "  \n");  
document.write("Simple Interest: " + calculateSimpleInterest(principle3, 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  
 Where,  
 P = Principle Amount  
 R = Rate  
 T = Time

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

Даны P, R и T. Нужно вычислить сложный процент. Пример: P=1000, R=7, T=2 → Compound Interest ≈ 144.9.

Программа на C++ для расчёта сложного процента

// C++ program to calculate compound interest  
// for given principle amount, time, and rate of interest.  
#include   
using namespace std;  
  
// Function to calculate compound interest  
float calculateCompoundInterest(float principle, float rate, float timePeriod)  
{  
 double amount = principle * (pow((1 + rate / 100), timePeriod));  
 return amount - principle;  
}  
  
int main()  
{  
 float principle1 = 1000;  
 float rate1 = 7;  
 float timePeriod1 = 2;  
 cout << "Test case: 1" << endl;  
 cout << "Principle amount: " << principle1 << endl;  
 cout << "Rate of interest: " << rate1 << endl;  
 cout << "Time period: " << timePeriod1 << endl;  
 cout << "Compound Interest: " << calculateCompoundInterest(principle1, rate1, timePeriod1) << endl;  
  
 float principle2 = 5000;  
 float rate2 = 5;  
 float timePeriod2 = 1;  
 cout << "Test case: 2" << endl;  
 cout << "Principle amount: " << principle2 << endl;  
 cout << "Rate of interest: " << rate2 << endl;  
 cout << "Time period: " << timePeriod2 << endl;  
 cout << "Compound Interest: " << calculateCompoundInterest(principle2, rate2, timePeriod2) << endl;  
  
 float principle3 = 5800;  
 float rate3 = 4;  
 float timePeriod3 = 6;  
 cout << "Test case: 3" << endl;  
 cout << "Principle amount: " << principle3 << endl;  
 cout << "Rate of interest: " << rate3 << endl;  
 cout << "Time period: " << timePeriod3 << endl;  
 cout << "Compound Interest: " << calculateCompoundInterest(principle3, 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 principle amount, time, and rate of interest.  
  
# Function to calculate compound interest  
def calculateCompoundInterest(principle, rate, timePeriod):  
    amount = principle * (pow((1 + rate / 100), timePeriod))  
    return amount - principle  
  
principle1 = 1000  
rate1 = 7  
timePeriod1 = 2  
print("Test case: 1")  
print("Principle amount:", principle1)  
print("Rate of interest:", rate1)  
print("Time period:", timePeriod1)  
print("Compound Interest:", calculateCompoundInterest(principle1, rate1, timePeriod1))  
  
principle2 = 5000  
rate2 = 5  
timePeriod2 = 1  
print("Test case: 2")  
print("Principle amount:", principle2)  
print("Rate of interest:", rate2)  
print("Time period:", timePeriod2)  
print("Compound Interest:", calculateCompoundInterest(principle2, rate2, timePeriod2))  
  
principle3 = 5800  
rate3 = 4  
timePeriod3 = 6  
print("Test case: 3")  
print("Principle amount:", principle3)  
print("Rate of interest:", rate3)  
print("Time period:", timePeriod3)  
print("Compound Interest:", calculateCompoundInterest(principle3, 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 principle amount, time, and rate of interest.  
  
  
// Function to calculate compound interest  
function calculateCompoundInterest(principle, rate, timePeriod) {  
 var amount = principle * (Math.pow((1 + rate / 100), timePeriod));  
 return amount - principle;  
}  
  
var principle1 = 1000;  
var rate1 = 7;  
var timePeriod1 = 2;  
document.write("Test case: 1" + "  \n");  
document.write("Principle amount: " + principle1 + "  \n");  
document.write("Rate of interest: " + rate1 + "  \n");  
document.write("Time period: " + timePeriod1 + "  \n");  
document.write("Compound Interest: " + calculateCompoundInterest(principle1, rate1, timePeriod1) + "  \n");  
  
var principle2 = 5000;  
var rate2 = 5;  
var timePeriod2 = 1;  
document.write("Test case: 2" + "  \n");  
document.write("Principle amount: " + principle2 + "  \n");  
document.write("Rate of interest: " + rate2 + "  \n");  
document.write("Time period: " + timePeriod2 + "  \n");  
document.write("Compound Interest: " + calculateCompoundInterest(principle2, rate2, timePeriod2) + "  \n");  
  
var principle3 = 5800;  
var rate3 = 4;  
var timePeriod3 = 6;  
document.write("Test case: 3" + "  \n");  
document.write("Principle amount: " + principle3 + "  \n");  
document.write("Rate of interest: " + rate3 + "  \n");  
document.write("Time period: " + timePeriod3 + "  \n");  
document.write("Compound Interest: " + calculateCompoundInterest(principle3, 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

Практические советы и распространённые ошибки

  • Форматирование валюты: при выводе сумм укажите символ валюты и локаль (в России ₽, формат с двумя знаками после запятой). Это чисто презентационный шаг и не влияет на расчёт.
  • Точность: при работе с деньгами избегайте float/double для финальных сумм. Используйте Decimal (Python), fixed-point или целые копейки (сохраняйте в копейках/центах) и библиотечные средства для точного округления.
  • Частота начисления: приведённая формула сложного процента предполагает ежегодное начисление. Если начисление происходит чаще (ежемесячно, ежедневно), используйте (1 + R/(100n))^(nT), где n — число начислений в году.

Важно: если ставка уже дана в десятичном формате (например, 0.07), не делите на 100 снова.

Когда эти формулы не подходят

  • Налоговые вычеты, комиссии и дополнительные взносы не учитываются простыми формулами.
  • Для плавающих ставок нужно моделировать изменение R во времени и применять периодические расчёты.
  • Для сложных финансовых инструментов (аннуитеты, облигации с купонами) используйте специализированные формулы или финансовые библиотеки.

Альтернативные подходы и улучшения кода

  • Для точности в Python: модуль decimal.Decimal. В C++: использовать int64 для центов или библиотеку boost::multiprecision. В JavaScript: BigInt для целых или библиотеки вроде decimal.js.
  • Добавьте проверку входных данных: отрицательные значения, нулевой период, нечисловые вводы.
  • Разделяйте представление и расчёт: функция возвращает числовой результат, а форматирование валюты делайте в слое вывода.

Быстрые эвристики и трюки

  • Правило 72: приблизительно оценит, за сколько лет инвестиция удвоится при годовой ставке R в процентах: годы ≈ 72 / R. (Это приближённая оценка для небольших ставок.)

Тестовые случаи и критерии приёмки

  • Нулевой период: T = 0 → процент = 0.
  • Нулевая ставка: R = 0 → процент = 0.
  • Большие значения: проверьте переполнение типов (особенно в C++).
  • Проверяйте формат вывода: две цифры после запятой для валют.

Краткий глоссарий (1 строка)

  • Принципал: начальная сумма денег; ставка: годовой процент; сложный процент: проценты на проценты.

Итоги

  • Простые формулы легко реализовать на любом языке.
  • Для финансовых применений критична точность и форматирование.
  • При ежемесячном/ежедневном начислении используйте модифицированную формулу с n начислений в году.

Краткое объявление: если вы начинаете изучать программирование, простые задачи вроде расчёта процентов отлично подходят для практики. Многие ресурсы, включая freeCodeCamp и Khan Academy, предлагают бесплатные уроки по основам.

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

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

Ускорение загрузок в Microsoft Store
Windows

Ускорение загрузок в Microsoft Store

Как подарить приложение из Microsoft Store на Рождество
Подарки

Как подарить приложение из Microsoft Store на Рождество

Исправить ошибку 0x80072F30 в Microsoft Store
Windows

Исправить ошибку 0x80072F30 в Microsoft Store

Microsoft Store не скачивает игры — что делать
Windows

Microsoft Store не скачивает игры — что делать

Исправить ошибку Microsoft Store 0xC002001B
Windows

Исправить ошибку Microsoft Store 0xC002001B

Установка MSIX/Appx и обход ошибки App Installer
Windows

Установка MSIX/Appx и обход ошибки App Installer