C#字符串插值中调用函数的正确语法求助
解决C#字符串插值中调用Math.Round的语法问题
嘿,我看到你作为C#新手,在尝试用字符串插值替代常规写法时遇到了Math.Round调用的问题,这很常见,咱们来快速搞定它!
首先,你原来的代码里,这行输出语句的写法是错误的:
Console.WriteLine($"The final value is: (Math.Round,2){Dolar} dólars");
错误原因
字符串插值的{}内部需要是有效的C#表达式,你这里的(Math.Round,2)既没有指定要四舍五入的目标值,也不符合方法调用的语法——方法调用需要遵循方法名(参数1, 参数2...)的格式。
正确的写法
你需要把要四舍五入的变量Dolar作为第一个参数传给Math.Round,小数位数2作为第二个参数,然后把整个方法调用放在插值的{}里:
Console.WriteLine($"The final value is: {Math.Round(Dolar, 2)} dólars");
修改后的完整代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { decimal Euro, Dolar; decimal tax = 1.19590m; Console.WriteLine("Convert euro into dólar- day 06/05/2018.\nWhat is the amount in euros? "); Euro = decimal.Parse(Console.ReadLine()); Dolar = Euro * tax; // 修正后的输出语句 Console.WriteLine($"The final value is: {Math.Round(Dolar, 2)} dólars"); Console.ReadKey(); } } }
简单来说,字符串插值的{}就像一个小型的代码执行区域,你可以直接在这里写变量、调用方法、甚至简单的运算,只要符合C#语法就行~
内容的提问来源于stack exchange,提问作者Leonardo Guimarães
相关产品推荐
相关产品推荐

