How to display a fixed number of digits in C++ without rounding - c++

I have this code (very basic):
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a = 0.0,
b = 0.0,
c = 0.0;
cout<<"Input a: ";
cin>>a;
cout<<"input b: ";
cin>>b;
cout<<endl;
c = a / b;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
return 0;
}
When I enter two numbers (say, a = 513 and b = 791) I get 0.65. Calculator shows that the correct answer is 0.648. I understand that my code rounds up the last decimal number but this is not what I want.
How can I get it to where it just stays as 0.64 and not 0.65?

If you would like to truncate the value to two decimal places, you can multiply it by 100, truncate to integer, and then divide by 100, like this:
c = a / b;
c = floor(100 * c) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
Demo on ideone.

You can use trunc to truncate to a certain number of digits:
c = a / b;
// truncate past two decimals:
c = trunc(c * 100) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
of for a generic function:
int trunc(double val, int digits)
{
double pow10 = pow(10,digits);
return trunc(val * pow10) / pow10;
}
then use
cout << "Result: " << fixed << setprecision(2) << trunc(c,2) << endl;

Related

How to input text in the struct variable and then compare it?

By the task I need to calculate the percent of foreign excellent students (so the country of origin isn't "Ukraine" and the mean mark is greater than 3). But it wouldn't work and I don't know if I input text in the struct variable correctly and than compare it. Please explain this.
The code:
#include <iostream>
#include <ctime>
#include <Windows.h>
#include <cmath>
#include <iomanip>
using namespace std;
struct Student {
char country[15];
int course;
float meanMark;
};
int main() {
Student s[4];
//strcpy_s(s.country, "hjkhj");
//s.country = "ffff";
for (int i = 0; i < 4; i++) {
cout << "Student" << i + 1 << ": " << "\n";
std::cin >> s[i].country;
cin >> s[i].course;
cin >> s[i].meanMark;
}
char u[8] = "Ukraine";
int k = 0;
for (int i = 0; i < 4; i++) {
if (s[i].country != u && s[i].meanMark > 3) {
k++;
}
}
float percent = k / 4 * 100;
cout << "percent = " << percent << "%" << endl;
}
Here is the input:
First goes the country of origin, than course, than mean mark
https://i.stack.imgur.com/kzdKz.png
Here is the output:
The result should be 25%
https://i.stack.imgur.com/7lhNd.png
I think that what u need is to modify the line where you calculate the percentage to
float percent = k / 4.0 * 100.0;
Okay so i changed char to string and it didn't work again, but then i changed places with / 4 and * 100 so the equation looks like float percent = k * 100 / 4;.... and it worked...

Float Point Number Rounding with round and pow functions

I am trying to write a program that rounds a number to a certain decimal place that was specified by the user. It is a requirement to do this with both cout.fset and cout.precision, as well as with round and pow functions. In the end, the output of the program should be something like this:
123.4567
2
123.46
123.46
My main function used cout.fset and cout.precision, and it works fine. The problem is my double rounding function which uses round and pow. For some reason I am getting the following output:
123.4567
2
123.46
0.00
Why is it printing just zeros in that last line? I am new to programming and C++ as a whole so I would appreciate your help. Thank you. (I have a feeling it is a minor/beginner mistake I am overlooking but this is the extent of my knowledge at the moment)
#include <iostream>
#include <math.h>
using namespace std;
double rounding(int pp){
double d;
double k = std::pow(10, pp);
return std::round(d * k) / k;
}
int main(){
double p;
double d, round;
cin >> d;
cin >> p;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(p);
cout << d << endl;
round = rounding(d);
cout << round << endl;
return 0;
}
d in the rounding function is not initialized and have indeterminate value.
Try this:
#include <iostream>
#include <math.h>
using namespace std;
double rounding(double d, int pp){
double k = std::pow(10, pp);
return std::round(d * k) / k;
}
int main(){
double p;
double d, round;
cin >> d;
cin >> p;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(p);
cout << d << endl;
round = rounding(d, d);
cout << round << endl;
return 0;
}

Getting wrong results after simple multiplication - C++

So, what needs to be done is: enter a real number and print the sum of its first 4 digits after the decimal point. E.g.: I enter 5.1010. I get to the point where I need to multiply 0.1010 by 10000 so it can become an integer, but the result I'm getting is 1009 instead of 1010 and everything falls apart after that.
I'd be forever thankful if someone can explain to me why does that happen.
#include<iostream>
using namespace std;
int main()
{
double n;
cout<<"Enter a positive real number: ";
do
{
cin>>n;
if(n<=0) cout<<"The number must be positive, enter again: ";
}while(n<=0);
//storing the fractional part in a var
int y=n;
double fr=n-y;
//turning the fractional part into an integer
int fr_int=fr*10000;
cout<<fr_int<<endl;
//storing each of the digits in a var
int a=fr_int/1000;
int b=fr_int/100%10;
int c=fr_int/10%10;
int d=fr_int%10;
cout<<"The sum of the first 4 digits is: " << a+b+c+d;
return 0;
}
You could simply change the code as follows, then it should be working.
n *= 10000;
int Integer = n;
int i = 4;
int sum = 0;
while(i--)
{
sum += (Integer%10);
Integer /= 10;
}
std::cout << "The sum of the first 4 digits is: " << sum;
Here is the output: https://www.ideone.com/PevZgn
Update:A generalized soln would be using std::string. However, would be great if the code is capable of handling exceptions in the case of non-numeric has been submitted by the user.
#include <iostream>
#include <string>
int main()
{
std::string Number;
double tempNum = 0.0;
std::cout << "Enter a positive real number: ";
do
{
std::cin >> Number;
tempNum = std::stof(Number);
if(tempNum <= 0)
std::cout << "The number must be positive, enter again: ";
}while(tempNum <= 0);
bool Okay = false;
int sum = 0;
int i = 4;
for(const auto& it: Number)
{
if(Okay && i > 0)
{
sum += static_cast<int>(it - '0');
--i;
}
if(it == '.') Okay = true;
}
std::cout << "The sum of the first 4 digits is: " << sum;
return 0;
}
I think you should add 0.5 before casting because the compile will always truncate the number.
In C++11 you can use std::round.
Floating points and doubles in C++ aren't able to represent all decimal numbers accurately. In particular, 0.1, it cannot represent faithfully.
If you must be guaranteed that you get accurate results, you should either use fixed point math or a bignumber library.

c++ Converting octal fraction to decimal fraction?

I'm currently working on a program that is meant to take an octal fraction as an input and convert it to a decimal fraction. So far, I have the part of code that will convert the portion before the decimal point to decimal, just not the floating points after the decimal point. I was trying to use modulus, but was unsuccessful because of my variable being a float.
Is there a way to convert the remaining numbers after the decimal point to decimal from octal? I have posted my code below. Any help is appreciated. Thanks!
int main()
{
float num;
int rem = 0;;
int dec = 0;
int i = 0;
cout << "Please enter a number with a decimal point: ";
cin >> num;
double ohalf = num - (int)num;
int half = num;
while (half != 0)
{
rem = half % 10;
half /= 10; //Converts first have to decimal
dec += rem *= pow(8, i);
i++;
}
cout << dec;
i = -1;
while (ohalf != 0)
{
rem = ohalf *pow(8, i); //Converts second half to decimal. *This is where I am stuck*
i--;
}
cout << rem;
_getch();
return 0;
}
Going with the idea that one can remove the decimal point just by multiplying with the base often enough:
"123.456" in base 16
=> BASE16("1234.56")/16
=> BASE16("12345.6")/(16*16)
=> BASE16("123456")/(16*16*16)
or
"123.456" in base 8
=> BASE8("1234.56")/8
=> BASE8("12345.6")/(8*8)
=> BASE8("123456")/(8*8*8)
So all we need to know is the number of places behind the decimal point.
Then we can remove it and use std::stoi to convert the remaining string in the wanted base.
As a last step we need divide again through base^number_of_places_after_decimal.
Putting everything together you get something like this:
#include <iostream>
#include <string>
#include <cmath>
using std::cout;
using std::cin;
using std::string;
int main()
{
int base = 8;
string value;
cout << "Please enter a number with a decimal point: ";
cin >> value;
size_t ppos = value.find('.');
if (ppos != string::npos) {
value.replace(ppos,1,"");
} else {
ppos = value.size();
}
size_t mpos = 0;
double dValue = (double)std::stoi(value, &mpos, base);
if (mpos >= ppos)
{
dValue /= std::pow(base, (mpos - ppos));
}
std::cout << dValue << '\n';
return 0;
}
If you're confident that both the integer and fractional parts of your floating-point value won't overflow the range of long long int, you could parse both parts separately with std::stoll(), then divide the fractional part by the appropriate power of 8:
#include <cmath>
#include <stdexcept>
#include <string>
double parse_octal_fraction(const std::string s)
{
std::size_t dotpos;
auto whole = std::stoll(s, &dotpos, 8);
if (dotpos+1 >= s.length())
// no fractional part
return whole;
std::size_t fract_digits;
auto frac = std::stoll(s.substr(dotpos+1), &fract_digits, 8);
if (s.find_first_not_of("01234567", dotpos+1) != std::string::npos)
throw std::invalid_argument("parse_octal_fraction");
return whole + frac / std::pow(8, fract_digits);
}
#include <iostream>
int main()
{
for (auto input: { "10", "0", "1.", "0.4", "0.04", "1.04", "1.04 ", "1. 04"})
try {
std::cout << input << " (octal) == " << parse_octal_fraction(input) << " (decimal)" << std::endl;
} catch (const std::invalid_argument e) {
std::cerr << "invalid input: " << e.what() << " " << input << std::endl;
}
}
The test inputs shown give this output:
10 (octal) == 8 (decimal)
0 (octal) == 0 (decimal)
1. (octal) == 1 (decimal)
0.4 (octal) == 0.5 (decimal)
0.04 (octal) == 0.0625 (decimal)
1.04 (octal) == 1.0625 (decimal)
invalid input: parse_octal_fraction 1.04
invalid input: parse_octal_fraction 1. 04
in your code
while (ohalf != 0)
{
rem = ohalf *pow(8, i); //Converts second half to decimal. *This is where I am stuck*
i--;
}
ohalf will never be equal to zero so It may have lead to infinite loop

Decimals not showing up in money counter in C++

I have written a C++ program (supposed to be a money counter), I'm having some trouble with my code, I need the decimals to show up. I use cout instead of printf if that matters.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
// Strings and Integers
int dollars;
int pennies;
int nickles;
int quarters;
int halfDollars;
int dimes;
int fiveBill;
int tenBill;
int twentyBill;
int fiftyBill;
int hundredBill;
// Coin/Bill Amounts
int penny = 0.01;
int dollar = 1.00;
int nickle = 0.05;
int quarter = 0.25;
int halfDollar = 0.50;
int dime = 0.10;
int five = 5.00;
int ten = 10.00;
int twenty = 20.00;
int fifty = 50.00;
int hundred = 100.00;
// Enter Amount
cout << "Count your money!\n\n" << endl << "Hundred Dollar Bills: ";
cin >> hundredBill;
cout << "\nFifty Dollar Bills: ";
cin >> fiftyBill;
cout << "\nTwenty Dollar Bills: ";
cin >> twentyBill;
cout << "\nTen Dollar Bills: ";
cin >> tenBill;
cout << "\nFive Dollar Bills: ";
cin >> fiveBill;
cout << "\nOne Dollar Bills: ";
cin >> dollars;
cout << "\nHalf-Dollars: ";
cin >> halfDollars;
cout << "\nQuaters: ";
cin >> quarters;
cout << "\nDimes: ";
cin >> dimes;
cout << "\nNickles: ";
cin >> nickles;
cout << "\nPennies: ";
cin >> pennies;
// Add Together
cout << (hundred * hundredBill) + (fifty * fiftyBill) + (twenty * twentyBill) + (ten * tenBill) + (five * fiveBill) + (dollars * dollar) + (halfDollar * halfDollars) + (quarter * quarters) + (dime * dimes) + (nickle * nickles) + (penny * pennies);
system("PAUSE");
return 0;
}
Your problem:
int penny = 0.01;
penny is an int, the name is short for 'integral value'. 0.01 is of type double. If you assign a double (either as literal or from another variable) to any form of int (int, long int, short int, ...), only the integral part is assigned and the decimals are dropped (simply dropped, no rounding occurs - no matter how close the value is to the next greater integral one).
So penny actually holds only 0. Alike the other variables, dollar is 1, nickle again 0, ...
You have now two choices. Either, you convert all numbers to double, or you do a little trick by assigning all values in cents:
int penny = 1;
int dollar = 100;
This is what I would prefer. Then only when it comes to outputting you would do appropriate formatting:
printf("the value of my variable is %d.%.2d $\n", value / 100, value % 100);
Edit:
As many prefer outputting via std::cout and this gets rather a hassle, a way to do it conveniently would be the following:
class Formatter
{
int value;
friend std::ostream& operator<<(std::ostream& s, Formatter f);
public:
Formatter(int value)
: value(value)
{
}
};
typedef Formatter F, M;
std::ostream& operator<<(std::ostream& s, Formatter f)
{
char c = s.fill();
return s << f.value / 100 << '.'
<< std::setfill('0') << std::setw(2) << f.value % 100
<< std::setfill(c); // restore previous fill character!
}
Typedef is not necessary, of course, just to illustrate other names – select any one that seems most appropriate to you (F: Formatter, M: Money, D: Dollar, ...). Usage then:
std::cout << F(penny) << std::endl;
As stated, the problem is that you are trying to assign a decimal value to an integer variable.
What occurs, is that your input (in the case of decimal values) can either be interpreted as a double or a float -type variable by the compiler. During the assignment of the given input however, int or fully, an integer, can only hold a value without a fractional component. Compiler takes note of this, and simply narrows your given input into a value the int variable can hold. The compiler isn't interested about anything after the decimal point, and simply discards the rest.
Thus,
int a = 3.5 // int can't hold the decimal 0.5, narrows into 3
int b = 3 // int can hold this, no narrowing
double d = 3.5 // double can hold this, no narrowing
float f = 3.5 // float can hold this, no narrowing
A good way would be to replace all your integer variables with the type double. In this simple a program, you shouldn't have the need to use printf to format the input.
And in the case you are wondering, why would I want to use double instead of float.
Here is some additional information:
https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double
Should I use double or float?
If you want to keep integers, cast the result to a float or double. Then set precision to 2 digits and fixed format.
#include <iostream>
#include <iomanip>
...
float total = (float) ((hundred * hundredBill) + (fifty * fiftyBill) + (twenty * twentyBill) + (ten * tenBill) + (five * fiveBill) + (dollars * dollar) + (halfDollar * halfDollars) + (quarter * quarters) + (dime * dimes) + (nickle * nickles) + (penny * pennies));
cout << std::setprecision(2) << std::fixed << total << endl;
I use "cout" instead of "printf" if that matters.
No it won't matter with whatever output you were expecting.
Use all the variables you want to manipulate w.r.t. decimals as 'double' data type.