2
\$\begingroup\$

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:

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 <iostream>

using namespace std;
void main()
{
    double principle, rate, interest;
int days;
cout << "Enter principle (-1 to end)";
cin >> principle;
while (principle != -1)
{
    cout << "Enter annual interest rate(as a decimal)";
    cin >> rate;

    cout << "Enter number of days";
    cin >> days;

    interest = principle * rate / 365 * days;
    cout << "Interest is "<< interest;
    cout << "Enter principle (-1 to end)";
    cin >> 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.

\$\endgroup\$
  • \$\begingroup\$ I'm still confused as to why someone would teach about using void main. But at least you know that it's wrong. \$\endgroup\$ – Jamal Sep 6 '16 at 3:26
  • \$\begingroup\$ I asked the same thing as well,but from what I was told today it's to just get the basics down. I am using the proper way while I practice on my own time. \$\endgroup\$ – Kamanzi Munroe Sep 7 '16 at 17:11
5
\$\begingroup\$
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.