Why does this C++ program round double values and not print the whole string?

c++ round to significant figures
c++ round to 3 decimal places
c++ rounding decimals
print double in c
how to print float value in c++
setprecision c++
c++ print whole double
how to print negative double value in c++

I was working on a HackerRank problem and I could not figure out why the C++ code round the double values when I am adding them and why it does not take in/print the entire string input it is given.

The code is supposed to take in an integer input (from one line), a double input (from another line), and a string input (also, from another line). Then it is supposed to print out the sum of the int input and 4, the sum of the double input and 4.0, and concatenate the string "HackerRank" to the beginning of the input string.

Here's the code I have:

#include <iostream>
#include <iomanip>
#include <limits>

int main(){
    int i = 4;
    double d = 4.0;
    string s = "HackerRank";
// Declare second integer, double, and String variables.

// Read and save an integer, double, and String to your variables.
// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.

// Print the sum of both integer variables on a new line.

// Print the sum of the double variables on a new line.

// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.

    int a;
    double b;
    string c;

    cin >> a; 
    cin >> b;
    cin >> c;


    a = a + i;
    b = b + d;

    cout << a << endl;
    cout << b << endl;
    cout << "" + s + c;

    return 0;
}

For the following input:

12
4.0
is the best place to learn and practice coding!

I got the output:

16
8
HackerRank is

When this is the expected output:

16
8.0
HackerRank is the best place to learn and practice coding!

The answer to your 2 questions:

Firstly, when you add a value of type int to a value of type float/string, the result will be of type int. This explains why you the output is 8 and not 8.0. This same rule applies to multiplication, division, and subtraction. Whenever an int is operated on by a float/double value or vice versa, the result is always of type int. Therefore, you should change the initialization of your d value to:

    double d = 4.0; // Or float d = 4.0

By the way, you cannot add a decimal point to a value of type int and expect it to be a floating point/double value. The data type of the variable that stores the value must be defined/initialized with a certain data type.

Secondly, your code does not print the desired string as you are using the wrong function to get the string as input from the user. While cin is the norm to be used in input, it does not work so well with variables of type "string". The reason for this is because cin only accepts one word; one continuous int, floating point value, char, etc..., and it cannot accept an entire sentence with spaces in between because it just stops reading after it sees a space; that's the rules of cin. To bypass this problem, you'll need another function, and that is

    getline(cin, variable_to_store_data);

instead of doing:

    cin >> c;

Do this:

    getline(cin, c);

This way, the entire sentence you inputted will be stored in the variable and not just the first word of the sentence. The getline does not ignore the words in a sentence that come after the first one; it reads all of the user input till the point he/she hits Enter, and it then stores the entire value in the variable (that's the second parameter).

By the way, if you want to output multiple things in one cout line, then do it using the following template:

    cin << a << ... << z << endl; // endl is optional; depends on your needs

Avoid using the method you used above:

    cout << "" + s + c;

Do it this way:

    cout << "" << s << c; // Why do you have "" at the begninning? That prints nothing. You can take that off also.

On a side note, getline() also has a lot of other functions, such as reading lines from a file. Read more about it online; there are lots of resources available.

Hope this answers your question.


EDIT: To make the program work, you'll actually have to add another line to ignore the enter hit at the end of the cin >> b; command, because that saves as the string in c. Therefore, do this:

    cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
    getline(cin, c);

The line I just added ignores the newline character hit at the end of the cin >> b command. This way, the compiler goes on to ask the user for the string to be stored in c. I've tried this code, and it works as it should.

Another thing, change your output statement to;

    cout << "" << s << " " << c << "." << endl;

This makes the string easier to read, and it adds a space between variable s and variable c during output. Hope this helps!

Printf format strings, Learn all about the C format specifier mini-language and become an expert at producing In this string, the %d indicates that the value to be displayed at that point in the is that you want to print d as an double; but d is not a double, it is a long double. If the number provided has more precision than is given, it will round. round( ) function in C returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from ”.1 to .5″, it returns integer value less than the argument. If decimal value is from “.6 to .9″, it returns the integer value greater than the argument.

This code will work...

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    int i2;
    double d2;
    string s2;

    cin>>i2;
    cin>>d2;

    cin.ignore();
    getline(cin, s2);

    cout<<i2+i<<endl;
    cout.precision(1);
    cout << fixed << d+d2 << endl;
    cout<<s+s2;
    return 0;
}

Setting decimal precision in C, Rounding is not required. C program to set precision in floating point numbers In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). in C/C++ · Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and first_page How to split a string in C/C++, Python and Java? Rounding Floating Point Number To two Decimal Places in C and C++ How to round off a floatig point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53

You can use the function 'getline' to realize it.

And the following example is well done on VS2013.

#include <string>
#include <iostream>
using namespace std;
int main(){
    string c;
    getline(cin, c); // is there anybody ?
    cout << "Hello, " + c; // Hello, is there anybody ?
    system("pause");
    return 1;
}

round() in C++, round() in C++ Parameters: x, value to be rounded double round (double x); float round (float x); long Here, in the above program we have just calculated the nearest integral value of We usually work with just two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal. To print the string, we have used puts (name);. Note: The gets () function can also be to take input from the user. However, it is removed from the C standard. It's because gets () allows you to input any length of characters. Hence, there might be a buffer overflow.

cin>>b;

use cin.ignore(); and then getline(cin, string_name);

This will read the complete string.

C Basics - C Programming Tutorial, Comments are not programming statements and are ignored by the compiler, but they int : for integers (whole numbers) such as 123 and -456 ;; double : for note that char '1' is different from int 1 , short 1 , float 1.0 , double 1.0 , and String "​1" . C programs use function printf() of library stdio to print output to the console​. The double is a fundamental data type built into the compiler and used to define numeric variables holding numbers with decimal points. C, C++, C# and many other programming languages recognize the double as a type. A double type can represent fractional as well as whole values.

C - round() function, Specifiers · Complete Tutorial of Array in C · C - String · C - Pointer · C - Function round( ) function in C returns the nearest integer value of the float/​double/long double If decimal value is from ”.1 to .5″, it returns integer value less than the argument. ”math.h” header file supports round( ) function in C language. double has 2x more precision then float. float is a 32 bit IEEE 754 single precision Floating Point Number1 bit for the sign, (8 bits for the exponent, and 23* for the value), i.e. float has 7 decimal digits of precision. double is a 64 bit IEEE 754 double precision Floating Point Number (1 bit for the sign, 11 bits for the exponent, and 52

Introductory C with C++, A conversion specifier is a special code that indicates the type of conversion that needs to take place on a listed For example, the conversion specifier for an integer value is a %d. For a long double it is %Lf. printf does not require an I modifier for a double. The precision modifier will round off the last place printed​. The use of istringstream would be more reasonable when the given string does not come from the console or a file directly, but perhaps as an argument in a function, or from a database or graphical component, through a framework that passes the string as a whole.

Printing double in C++, Today, I found some problems while trying to print a double values in C++. When I compile this code using command mingw32-g++.exe -O2 -Wl There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A Codeforces Round #638 (Div. 2) 3 days roll_no_56_junior → String hashing New comment​(s). In this C programming language tutorial we take another look at the printf function. We will look at how to use format specifiers to print formatted output onto the screen. The topics covered are; a little printf background, format specifiers and conversions, formatting of different types and format conversions of strings.

Comments
  • See stackoverflow.com/questions/388242/… for the answer to this question.
  • 1) 8, and 8.0 means exactly the same thing (no rounding involved). It's just a matter of representation. Use std::fixed, and std::setprecision I/O manipulators to achieve what you want. 2) You couldn't get the output of HackerRank is since, for specified input, cout << "" + s + c; would've produced HackerRankis. You never inserted a space in your string. And, if you want to read an entire line, use std::getline.
  • try 4.1 then it won't round as you guess
  • I did everything that you said and it works except that the getline(cin, c) doesn't do anything. It complies right but c isn't assigned a string. I know how getline works but I can't figure out why it is not working now.
  • @NiteshKartha I have updated my answer, check it at the bottom.
  • Thank you very much