Answer the question
In order to leave comments, you need to log in
How to switch from PHP to C# (not according to standard textbooks)?
Recently, at the Olympiad, there was a task where you need to sort through numbers from 100 to 999, sum up the digits of each number.
Also in tasks I needed array_merge() and array_unique() functions.
In PHP, the first task can be solved like this:
<?php
for($i=100; $i<=999; $i++){
Si=(string)$i; //в C# не получается явное преобразование
$sum[]=$i{0}+$i{1}+$i{2}; //в C# нет возможности выбирать букву из строки, по крайней мере, я не обнаружил
}
print_r($sum); //это не обязательно, просто чтоб код не был пустышкой
?>
Answer the question
In order to leave comments, you need to log in
You'll probably still have to read it.
1. Your print_r($sum) is supposed to throw at least a warning, since you created $sum in the loop and use it outside the loop. In sharps, it will not exist there.
2. Sharps have types. No one will create numbers as strings. There is no wash. It also makes no sense to convert the number back to a string.
Create a list with numbers (not strings) from 100 to 999.
No need to convert number to string (your method is so-so). You need to use the remainder of division by 10. For 650, it will return 11.
int sum = 0;
for (int n = x; n > 0; sum += n % 10, n /= 10);
var numberList = Enumerable.Range(100, 999).ToList();
var result = numberList.Select(x =>
{
int sum = 0;
for (int n = x; n > 0; sum += n % 10, n /= 10);
return sum;
});
;
explicit conversion fails in C#
Read documentation and books. And solve problems.
You must understand what strong typing is.
You can find all the digits of a 3-digit number using the remainder of the division.
In order to understand these principles, it is important to write programs in a strongly typed language for some time. I once wrote in Pascal - that was enough to understand many things.
PHP is for kids not because there are a lot of library functions.
Write some small project in C# and .NET
If you are interested in mobile development, you can try peeing on Xamarin for interest.
Find yourself a "teacher" (on freelancing.ru and other sites) and write to him on Skype for every question that arises in the process of writing a program.
It's quick and painless, but it costs money.
List<int> sum_array = new List<int>();
for(int i = 100; i <= 999; i++) {
string text_numbers = i.ToString();
var sum_of_elements = Int32.Parse(text_numbers[0]) + Int32.Parse(text_numbers[1]) + Int32.Parse(text_numbers[2]) ;
sum_array.Add(sum_of_elements);
}
Console.WriteLine("[{0}]", string.Join(", ", sum_array));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question