[HackerRank] Day 1: Data Types

Problem πŸ”—

Sample Input

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

Sample Output

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

Explanation

When we sum the integers 4 and 12, we get the integer 16. When we sum the floating-point numbers 4.0 and 4.0, we get 8.0. When we concatenate HackerRank with is the best place to learn and practice coding!, we get HackerRank is the best place to learn and practice coding!.

Solution

int main() {
    ...    
    int i2;
    double d2;
    string s2, tmp;

    // Get line and convert each data type
    getline(cin, tmp);
    i2 = stoi(tmp);
    
    getline(cin, tmp);
    d2 = stod(tmp);
    
    getline(cin, s2);
    
    // output 1
    cout << i + i2 << endl;

    // output 2
    cout << fixed;
    cout.precision(1);
    cout << d + d2 << endl;
    
    // output 3
    cout << s + s2 << endl;

    return 0;
}

stoi(s)κ³Ό stod(s)λ₯Ό μ‚¬μš©ν•΄μ„œ string을 int와 double둜 각각 λ³€ν™˜ν•˜μ˜€λ‹€.

cout << fixed;와 cout.precision(x);λ₯Ό μ‚¬μš©ν•΄μ„œ μ†Œμˆ˜μ μ„ κ³ μ •ν•˜κ³  1자리둜 ν‘œκΈ°ν•˜μ˜€λ‹€.

Leave a comment