整数与小数运算
Coddy 面向 C++ 开发者的 C# 课程的第 4 课,共 48 课。
C++ 和 C# 的 int 除法会向零截断,要保留小数,必须先进行类型转换。C# 还内置了 decimal 类型,可使用 m 字面量。标准 C++ 没有直接等价的 decimal 基本类型。选择数值模型对处理金钱很重要。
两个 int 相除时,结果会向零截断。如果需要得到小数结果,请在除法前将一个操作数转换为 double。decimal 使用十进制算术,并带有 m 字面量后缀,适用于后续的金钱计算。int 或 double 参数都不会自动变成任意精度整数。
C++ 参考
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
int main() {
cout << 5 / 2 << "\n";
cout << fixed << setprecision(1) << static_cast<double>(5) / 2 << "\n";
}
C# 的 Main 中的语句
Console.WriteLine((5 / 2).ToString());
Console.WriteLine(((double)5 / 2).ToString("0.0", CultureInfo.InvariantCulture));这些内容是重点教学片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关声明和语句。
参考输出:
2
2.5C# 输出:
2
2.5挑战
简单输入行包含整数 total 和 count。返回它们的浮点数商;如果 count 为零,则返回零。驱动程序会使用固定的小数点格式显示两位小数。
编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述行,调用 Exercise.Solve,验证输入未被修改,并在最后输出一个换行符。保留声明的 API。不要添加第二个 Main,也不要输出诊断信息。
亲手试试
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result.ToString("0.00", CultureInfo.InvariantCulture));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器