对于我的C#编程作业,我们必须编写一个程序,该程序允许用户输入一个整数并使用循环来打印出该整数的因数。
我得到了输出整数的程序。
问题是,例如,当我输入整数“ 24”时,我希望输出为
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
但是输出的结果是
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24 and
我不希望在因子列表的末尾添加额外的“和”
这是我的代码:
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
Console.Write(b + " ");
}
}
Console.ReadLine();
}
}
}
编辑:输出已的格式设置为
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
否则我将无法获得这份功课
答案 0 :(得分:2)
您可以枚举因子,然后使用Join
{p}来" and "
private static IEnumerable<int> Factors(int value) {
// Simplest, not that efficient
for (int i = 1; i <= value; ++i)
if (value % i == 0)
yield return i;
}
...
Console.Write(string.Join(" and ", Factors(24)));
或者您可以在打印因子(" and "
之前添加i
在之前,而不是在之后
int value = 24;
bool firstTime = true;
// Simplest, not that efficient
for (int i = 1; i <= value; ++i) {
if (value % i == 0) {
// print "and" before printing i
if (!firstTime)
Console.Write(" and ");
firstTime = false;
Console.Write(i);
}
}
答案 1 :(得分:0)
如何将数字加到setwd("<path>")
tinytex::latexmk("./nctikz-1.tex", install_packages = FALSE, clean = FALSE)
并在循环后打印:
List
答案 2 :(得分:0)
model = ..imported model..
seq_model = Sequential()
for layer in model.layers:
seq_model.add(layer)
答案 3 :(得分:0)
我建议您创建一个字符串并输出该字符串,因为它允许您使用它执行更多操作,然后执行以下操作:
int a, b;
string x="";
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
x=x + b.toString() +" and";
}
}
如果您知道结尾处始终是“ and”,则只需执行此操作
string x = x.Substring(0, x.Length - 3);
然后
Console.Write(x);
Console.ReadLine();