patterncppMinor
Calculating the interest on a series of loans
Viewed 0 times
theloanscalculatinginterestseries
Problem
I am a college student and started my first week of C++ and we were given an assignment to convert a Java program that calculate the interest on a series of loans given the amount of the principal, the annual interest rate, and the number of days in a sentinel loop into C++.
Here is what we were given:
This is what I have for the C++ converted code:
I would like to know if there is a better way to go about this, as in making my code more efficient. I am aware that I should not be using
Here is what we were given:
import java.util.Scanner;
public class ex311
{
public static void main(String[] args)
{
double principle, rate, interest;
int days;
Scanner sc = new Scanner(System.in);
System.out.print("Enter principle (-1 to end): ");
principle = sc.nextDouble();
while (principle != -1)
{
System.out.print("Enter annual interest rate (as a decimal): ");
rate = sc.nextDouble();
System.out.print("Enter number of days: ");
days = sc.nextInt();
interest = principle * rate / 365 * days;
System.out.printf("Interest is %.2f\n", interest);
System.out.print("\nEnter principle (-1 to end): ");
principle = sc.nextDouble();
}
}
}This is what I have for the C++ converted code:
#include
using namespace std;
void main()
{
double principle, rate, interest;
int days;
cout > principle;
while (principle != -1)
{
cout > rate;
cout > days;
interest = principle * rate / 365 * days;
cout > principle;
}
}I would like to know if there is a better way to go about this, as in making my code more efficient. I am aware that I should not be using
void main, but this is how we're being taught for the time being.Solution
-
Do not represent monetary amounts as a decimal type; use an integer type instead.
-
Try to avoid the use of
-
You could still allow the user to enter an interest rate and have the program convert it to a decimal, especially if the user doesn't know how to do this.
-
You could just have
Moreover, if you're going to "list" variables, have each one on a separate line. This is easier to read and avoids the possibility of needing to scroll horizontally.
Do not represent monetary amounts as a decimal type; use an integer type instead.
-
Try to avoid the use of
using namespace std.-
You could still allow the user to enter an interest rate and have the program convert it to a decimal, especially if the user doesn't know how to do this.
-
You could just have
days, rate, and interest declared or initialized within the loop. It's usually best to have variables kept in as close scope as possible.Moreover, if you're going to "list" variables, have each one on a separate line. This is easier to read and avoids the possibility of needing to scroll horizontally.
Context
StackExchange Code Review Q#140448, answer score: 5
Revisions (0)
No revisions yet.