When dividing (an element of a string made up of digits) by a digit, it always outputs 0. And if you try to calculate the remainder of the division using "%", then it outputs the same figure.
static void Main(string[] args)
{
Console.Write("Введите N: ");
int N = Convert.ToInt32(Console.ReadLine());
string str = "",STR = "";
Console.WriteLine(" Числа меньше N, делящиеся на каждую из своих цифр: ");
for (int i = 1; i < N; i )
{
STR ="" i;
for (int j = 0; j < STR.Length; j )
{
if (i % STR[j] == 0)
{
str = STR[j];
if (str.Length == STR.Length)
{
Console.Write(str.ToString() ", ");
}
}
if ( i % STR[j] != 0)
{ break; }
}
str = "";
}
}
I don't understand why it doesn't work..
CodePudding user response:
You are dividing an integer by a string when doing i % STR[j]
. That can't work. Be sure to divide and % by integers.
CodePudding user response:
public static void Main()
{
var maxNumber = 20;
// Let's get a range of numbers that can be enumerated
var range = Enumerable.Range(1, maxNumber);
// Let's get from the range only items that comply with a condition
// The condition here is a simple function
// that returns true or false
var result = range.Where(e => CheckNumber(e));
// Let's combine the result string
var resultString = string.Join(", ", result);
Console.WriteLine(" Числа меньше N, делящиеся на каждую из своих цифр: ");
Console.WriteLine(resultString);
}
public static bool CheckNumber(int n)
{
// The task is to check the divisibility
// Let's convert the number into a sting
// your way of "" i; is good but let's use a standart approach
var str = n.ToString();
// Bearing in mind that a string consists of chars that can be enumerated
// let's filter it.
// We don't take zeroes to avoid division by zero exception
// and check whether our n is divided without a remeinder or not
var nonDivisible = str.Where(e => int.Parse(e.ToString()) > 0 && (n % int.Parse(e.ToString())) != 0);
// If the filtered data is empty,
// our number comply with the rules,
// and we return true. false otherwise
return nonDivisible.Count() == 0;
}