简体   繁体   中英

C# Hackerrank code produces correct results on Data Types challenge in 30 days of code but says I'm wrong

Recently I have tried to solve Day 1 Data types lesson for the 30 days of Code challenge in hackerrank and I've run into a strange road block.The compiler keeps saying that my output is the wrong answer, but I print out the exact same integer double and string. the only thing that's different is that I don't have a decimal point on my double,which doesn't make sense because The only thing I've done is read from the input,convert the input from a string to a double and then add the two doubles together

Can you guys help? This is my C# code by the way.

using System;
using System.Collections.Generic;
using System.IO;



class Solution {
    static void Main(String[] args) {
        int i = 4;
        double d = 4.0;
        string s = "HackerRank ";

     //this is the start of my code,the top part is preset by hackerrank
int a=Convert.ToInt32(Console.ReadLine());
double x = Convert.ToDouble(Console.ReadLine());
string l = Console.ReadLine();

Console.WriteLine(a+i);
Console.WriteLine(d+x);
Console.WriteLine(s+l);

Console.ReadLine();

}
}

here is there input they want me to use that I am using:

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

Here is my output :

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

And The output they want:

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

as you can see my ".0" is missing for my double, any help?

You can use .ToString() with an overload to format your result:

Console.WriteLine((d+x).ToString("#.0"));

the 0 represents a default placeholder, if there is no decimal point it will add 0 . else it will show the actual value.

To answer your comments:

# represents any number preceding the .

Why does it strip the .0 in your case: according to MSDN, Console.WriteLine(double) represents the output as a string using the default ToString("G") overload:

The text representation of value is produced by calling the Double.ToString method. Source

The general ("G") format specifier converts a number to the more compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. Source

According to the documentation above, if you were to change your data type to decimal instead of double the .0 should be preserved.

尝试这个

Console.WriteLine("{0:F1}",d+x);

您可以添加 0.0 使其成为双倍值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM