0

Trying to change this C++ to Java

//The following pseudocode describes how to extract the dollars and cents from a
//price given as a floating - point value.For example, a price 2.95 yields values 2 and 95
//for the dollars and cents.
//Assign the price to an integer variable dollars.
//Multiply the difference price - dollars by 100 and add 0.5.
//Assign the result to an integer variable cents.
//Translate this pseudocode into a C++ program.Read a price and print the dollars
//and cents.Test your program with inputs 2.95 and 4.35.

#include<iostream>

using namespace std;

int main()
{
    cout << "Enter a price: ";
    float price;
    cin >> price;

    int dollars = (int)price;
    float cents = (price - dollars) * 100;

    cout << "That is " << dollars << " dollars and " << cents << " cents.";

    return 0;
}
3
Contributors
2
Replies
12
Views
2 Years
Discussion Span
Last Post by JamesCherrill
0

It won't work in java any better than it will in C++.
tenths and hundredths can't be represented exactly in a binary floating point representation, so this naive approach will always suffer from the risk of rounding or truncation errors.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.