练习
第一项挑战
此模块包含两项代码挑战。第一项挑战强制要求根据数据类型拆分数据,并相应地连接或添加数据。
编写代码以实现业务规则
循环访问值字符串中的每个值。
从以下代码行开始。
csharp
string[] values = { "12.3", "45", "ABC", "11", "DEF" };添加实现以下业务规则所需的所有代码:
业务规则:
- 规则 1:如果值是字母数字型,则连接它以形成消息
- 规则 2:如果值是数字,则将其添加到总计值
- 规则 3:确保结果与以下输出一致:
output
Message: ABCDEF
Total: 68.3代码
csharp
string[] values = { "12.3", "45", "ABC", "11", "DEF" };
string message = "";
decimal total = 0m;
foreach(string value in values){
decimal result = 0m;
if(decimal.TryParse(value, out result)){
total += result;
} else{
message += value;
}
}
Console.WriteLine($"Message: {message}\nTotal: {total}");
// Message: ABCDEF
// Total: 68.3答案
csharp
string[] values = { "12.3", "45", "ABC", "11", "DEF" };
decimal total = 0m;
string message = "";
foreach (var value in values)
{
decimal number;
if (decimal.TryParse(value, out number))
{
total += number;
} else
{
message += value;
}
}
Console.WriteLine($"Message: {message}");
Console.WriteLine($"Total: {total}");第二项挑战
考虑到收缩转换和扩大转换的影响,下面的挑战强制要求了解强制转换值的含义。
编写代码生成所需的输出
从以下代码开始:
csharp
int value1 = 12;
decimal value2 = 6.2m;
float value3 = 4.3f;
// Your code here to set result1
Console.WriteLine($"Divide value1 by value2, display the result as an int: {result1}");
// Your code here to set result2
Console.WriteLine($"Divide value2 by value3, display the result as a decimal: {result2}");
// Your code here to set result3
Console.WriteLine($"Divide value3 by value1, display the result as a float: {result3}");将代码注释替换为自己的代码来解决问题。
运行代码后,应会得到以下输出:
bash
Divide value1 by value2, display the result as an int: 2
Divide value2 by value3, display the result as a decimal: 1.4418604651162790697674418605
Divide value3 by value1, display the result as a float: 0.3583333代码
csharp
int value1 = 12;
decimal value2 = 6.2m;
float value3 = 4.3f;
int result1 = value1 / (Convert.ToInt32(value2));
Console.WriteLine($"Divide value1 by value2, display the result as an int: {result1}");
decimal result2 = value2 / (decimal)value3;
Console.WriteLine($"Divide value2 by value3, display the result as a decimal: {result2}");
float result3 = value3 / value1;
Console.WriteLine($"Divide value3 by value1, display the result as a float: {result3}");
// Divide value1 by value2, display the result as an int: 2
// Divide value2 by value3, display the result as a decimal: 1.4418604651162790697674418605
// Divide value3 by value1, display the result as a float: 0.3583333答案
csharp
int value1 = 12;
decimal value2 = 6.2m;
float value3 = 4.3f;
int result1 = Convert.ToInt32((decimal)value1 / value2);
Console.WriteLine($"Divide value1 by value2, display the result as an int: {result1}");
decimal result2 = value2 / (decimal)value3;
Console.WriteLine($"Divide value2 by value3, display the result as a decimal: {result2}");
float result3 = value3 / value1;
Console.WriteLine($"Divide value3 by value1, display the result as a float: {result3}");