C#使用循环生成具有正确算术关系的table
C# using loops to generate a table with correct arithmetic relationship
下面是ShowTab()方法,如何将动态数字和结果应用到table?
using System;
const int MAX = 4;
int cage = 500/total;
int month = 1;
int adults = 1;
int babies = 0;
int total = 1;
Console.WriteLine("Month\tAdults\tBabies\tTotal");
Console.WriteLine("{0, -10}{1, -10}{2, -10}{3, -10}", month, adults, babies, total);
for(int i = 0; i < MAX; i++) {
Console.writeLine(
}
也许我错过了什么;但如果它只是以某种方式格式化;像这样的东西应该可以完成工作:
int month = 1;
int adults = 1;
int babies = 0;
int total = 1;
Console.WriteLine ("header row"); // optional (if needed)
while (/* there is still cages to hold them */)
{
// print current state (-10 width chosen for example, negative for left align)
Console.WriteLine ($"{month, -10}{adults, -10}{babies, -10}{total, -10}");
// do the maths to update values
month = /* ... */;
adults = /* ... */;
babies = /* ... */;
total = /* ... */;
}
这是一个虚拟的 exemple,它说明了为什么我选择使用宽度格式说明符而不是制表符(如一条评论 link 中所暗示)。
下面是ShowTab()方法,如何将动态数字和结果应用到table?
using System;
const int MAX = 4;
int cage = 500/total;
int month = 1;
int adults = 1;
int babies = 0;
int total = 1;
Console.WriteLine("Month\tAdults\tBabies\tTotal");
Console.WriteLine("{0, -10}{1, -10}{2, -10}{3, -10}", month, adults, babies, total);
for(int i = 0; i < MAX; i++) {
Console.writeLine(
}
也许我错过了什么;但如果它只是以某种方式格式化;像这样的东西应该可以完成工作:
int month = 1;
int adults = 1;
int babies = 0;
int total = 1;
Console.WriteLine ("header row"); // optional (if needed)
while (/* there is still cages to hold them */)
{
// print current state (-10 width chosen for example, negative for left align)
Console.WriteLine ($"{month, -10}{adults, -10}{babies, -10}{total, -10}");
// do the maths to update values
month = /* ... */;
adults = /* ... */;
babies = /* ... */;
total = /* ... */;
}
这是一个虚拟的 exemple,它说明了为什么我选择使用宽度格式说明符而不是制表符(如一条评论 link 中所暗示)。