C#算法代码未通过测试用例

时间:2018-07-13 01:36:29

标签: c# algorithm

面临的挑战是根据给定的输入来计算一餐的总费用:

  1. 膳食费用(不含税或小费)(给出两倍)
  2. 提示百分比(以int形式给出)
  3. 税率(以整数表示)
  

注意:默认情况下,这些数据类型必须保持这种方式。我无法将其初始声明更改为double而不是int

给定步骤如下:

  1. 读取3个值的输入
  2. 使用tip = mealCost x (tipPercent / 100)
  3. 计算提示
  4. 使用tax = mealCost x (taxPercent / 100)
  5. 计算税金
  6. 通过添加mealCosttiptax计算总餐费。
  7. 四舍五入并打印出最终答案(作为“总用餐费用为totalCost美元。”)

所以我的程序遵循以下原则:

using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution {

    // Complete the solve function below.
    static void solve(double meal_cost, int tip_percent, int tax_percent) {
        double tip = meal_cost * (tip_percent / 100.0);
        double tax = meal_cost * (tax_percent / 100.0);

        double totalCost = (meal_cost + tip + tax);

        Console.WriteLine("The total meal cost is {0} dollars", Convert.ToInt32(totalCost));
    }

    static void Main(string[] args) {
        double meal_cost = Convert.ToDouble(Console.ReadLine());

        int tip_percent = Convert.ToInt32(Console.ReadLine());

        int tax_percent = Convert.ToInt32(Console.ReadLine());

        solve(meal_cost, tip_percent, tax_percent);
    }
}

但是,尽管我的输出是相同的(直到四舍五入为止),但HackerRank仍将我的解决方案在其测试用例(而非我的自定义测试用例)上标识为“失败”。有什么解释吗?

  

注意:HackerRank提供的公式实际上是(餐费)x税百分比/100。我只是写下了实现方式

2 个答案:

答案 0 :(得分:3)

您打了些错字。应该使用dollars时使用了dollars.

在对您的代码进行更改后,它在https://www.hackerrank.com/challenges/30-operators/problem处通过了。

答案 1 :(得分:-3)

查看输出。 totalCost的值输出为integer。由于meal_cost数据类型为double,可能大于integer的上限,因此您应将totalCost输出为double,而不要强制转换为integer

Console.WriteLine("The total meal cost is {0} dollars", totalCost);