static void Main() { double theta; //угол в радианах for (theta = 0.1; theta <= 1.0; theta = theta + 0.1) { Console.WriteLine("Синус угла {0} равен {1}", theta, Math.Round(Math.Sin(theta),2)); Console.WriteLine("Косинус угла {0} равен {1}", theta, Math.Round(Math.Cos(theta),2)); Console.WriteLine("Тангенс угла {0} равен {1}", theta, Math.Round(Math.Tan(theta),2)); } } 

Hello, dear. From above, the code calculates the sine cosine and the tangent of theta. The following answer is displayed on the console (approximately):

Sinus....
Cosine...
Tangent...
Sinus....
Cosine....
Tangent....
...........

And I need an answer like:

Sinus....
Sinus....
Sinus....
.......
Cosine....
cosine....
Cosine....
.......
Tangent....
Tangent....
Tangent....
.......

I can use the for function two more times, but it seems to me that this is not correct. Any idea how to do this without Nuba copies? I think the language has methods to use the function several times without unnecessary scribbling! But I do not know! I will be glad to any answers!

  • 2
    take the loop to the function - Grundy
  • 2
    Collect results and only then deduce as you need - vp_arth

7 answers 7

Solution to the forehead:

 double theta; //угол в радианах for (int foo = 0; foo < 3; foo++) { for (theta = 0.1; theta <= 1.0; theta = theta + 0.1) { switch (foo) { case 0: Console.WriteLine("Синус угла {0} равен {1}", theta, Math.Round(Math.Sin(theta), 2)); break; case 1: Console.WriteLine("Косинус угла {0} равен {1}", theta, Math.Round(Math.Cos(theta), 2)); break; case 2: Console.WriteLine("Тангенс угла {0} равен {1}", theta, Math.Round(Math.Tan(theta), 2)); break; } } } 

A variation on lambda:

 Func<string, Func<double, double>, int> solve = (string funcName, Func<double, double> func) => { for (double theta = 0.1; theta <= 1.0; theta = theta + 0.1) Console.WriteLine(String.Format("{0} угла {1} равен {2}", funcName, theta, Math.Round(func(theta), 2))); return 0; }; solve("Синус", Math.Sin); solve("Косинус", Math.Cos); solve("Тангенс", Math.Tan); 
  • one
    I liked it more! Simple and understandable (yes, I did not understand what a switch and case are, break, but that's not the point: D). - Tobi
  • very beautiful decision! - Senior Pomidor
  • four
    Brrrrrrrrrrrrrrrrrrrrr - Qwertiy
  • @Qwertiy Why brrr?) For me it would be better in the language made it possible to call functions again simple, small code (at least within the class. These are just beginner ideas and may seem silly and not only seem ...: D) like: for ( 1) (theta = 0.1; ........) Console.WriteLine (......); run for1; // small code to call the function Console.WriteLine (....); That's all. I just cannot understand how in the language there is no possibility to call already written functions, etc. things (of course, without unnecessary scribbling and headaches). - Tobi
  • one
    @Tobi, the language has almost everything you need. And you can call - there are answers. And brr because to do switch on an index inside for is a tin. Imagine that you have 3 items that need to be delivered to 3 different apartments in 3 houses. Now you enter the first house, find an apartment in it written on the first card, get up near the bell and check it, and the house on the card coincides with the house in which you found the apartment? Oops, no, let's go to the next one. Found But in the third we still go and check that it does not match. And again to the first, to carry the second premise ... And so 9 times. Good for you? - Qwertiy

Well, you can pervert.

 void Display(Func<double, double> f, string name) { for (double theta = 0.1; theta <= 1.0; theta = theta + 0.1) Console.WriteLine($"{name} угла {theta:F1} равен {f(theta):F2}"); } 
 Display(Math.Sin, "Синус"); Display(Math.Cos, "Косинус"); Display(Math.Tan, "Тангенс"); 

See how it works. We want to render the loop with the calculation of one trigonometric function in a separate method, and transfer the different parts as parameters.

Okay, what's different with us? Two things: a called function and a string with its name. Passing a string is simple, but how to pass a function? It turns out that functions can also be written to variables! For a function that takes a double argument and returns a double , the type will be Func<double, double> . We declare the parameter f this type. Now you can transfer the function Math.Sin to the Display method, as it is written in the example code.

Yes, and I still round up to two decimal places not through Math.Round (he may have potential problems, because not every number can be represented in double type with exactly two decimal places ), but through specifying the output format: F2 means I want to get 2 decimal places on output .

And I also use a fashionable chip called string interpolation .

  • four
    And what's the perversion? :-) Standard Approach: Method Allocation - Grundy
  • one
    @Grundy: The perversion is that for such a simple task it is too much code. And the whole auxiliary function. Perhaps three cycles easier. - VladD
  • 2
    I also like this solution, and the lines of code are no more than the rest, if desired, the initial value, the final value and the cycle step can also be transferred to the parameters and get a ready "library" method :) Yes, also send the output stream in the parameter :) - Andrey NOP
  • And I did not understand anything ...: (I would like to know how everything works here, but I think it will take a lot of bucks and time ... your time ...: D If you have free time and mood, please chew this code and feed the little ones, stupid chicks. XD - Tobi
  • one
    The problem with this approach is that the function is too simple for the delegate. Overhead costs will be high ... - Pavel Mayorov

Another option is to write the results to a string, then output in turn:

 string s1 = "", s2 = "", s3 = ""; for (theta = 0.1; theta <= 1.0; theta = theta + 0.1) { s1 += string.Format("Синус угла {0} равен {1}\n", theta, Math.Round(Math.Sin(theta), 2)); s2 += string.Format("Косинус угла {0} равен {1}\n", theta, Math.Round(Math.Cos(theta), 2)); s3 += string.Format("Тангенс угла {0} равен {1}\n", theta, Math.Round(Math.Tan(theta), 2)); } Console.Write(s1 + s2 + s3); 
  • It works and seems understandable, but this logic is alien to me. From above, the code with the switch is much nicer, but I liked your code too. I’m also willing to put a green check mark but only one. :( If there is time, briefly write why there \ n. Thank you for giving me some of your time.: 3 - Tobi
  • one
    \ n - Line feed - Andrew NOP
  • 2
    Adding lines ... - Qwertiy
  • A good option, just use StringBuilder instead of string - Ev_Hyper
  • Generally, of course, yes. But with 10 iterations, no one will notice the difference. - Andrey NOP

The conclusion is more correct to do in different cycles.

But it is better to have the calculation in one place and save the calculated values ​​into one list, and then work with it (including output to the console).

And for is not a function, but a language construct .

http://ideone.com/NztJ2O

 using System; using System.Collections.Generic; using static System.Math; public class Test { private class Vals { public double Theta; public double Sin; public double Cos; public double Tan; } public static void Main() { var data = new List<Vals>(); for (double theta = 0.1; theta <= 1.0; theta = theta + 0.1) data.Add(new Vals() { Theta = theta, Sin = Sin(theta), Cos = Cos(theta), Tan = Tan(theta) }); foreach (var val in data) Console.WriteLine("Синус угла {0} равен {1}", val.Theta, Math.Round(val.Sin, 2)); foreach (var val in data) Console.WriteLine("Косинус угла {0} равен {1}", val.Theta, Math.Round(val.Cos, 2)); foreach (var val in data) Console.WriteLine("Тангенс угла {0} равен {1}", val.Theta, Math.Round(val.Tan, 2)); } } 
  • Here, I vote for the transfer of a green check mark here. - vp_arth
  • @vp_arth why? - Ev_Hyper
  • This solution implements my comment to the post) The main reason is the presence of a separation of logic and output. - vp_arth
  • No, he won’t get green ... -.- The main thing for me is less code. And what else would I understand at least in this code. A novice asked a question and solve the problem at his level. I didn’t understand anything from this. I’ll put Like, but this is not interesting to me. - Tobi

http://ideone.com/h7Ih1l

 using System; using System.Linq; using static System.Math; public class Test { public static void Main() { var data = Enumerable.Range(0, 10).Select(x => x/10.0); Console.WriteLine(String.Join("\n", data.Zip(data.Select(Sin), (x, y) => String.Format("Синус угла {0} равен {1}", x, y)))); Console.WriteLine(String.Join("\n", data.Zip(data.Select(Cos), (x, y) => String.Format("Косинус угла {0} равен {1}", x, y)))); Console.WriteLine(String.Join("\n", data.Zip(data.Select(Tan), (x, y) => String.Format("Тангенс угла {0} равен {1}", x, y)))); } } 
  • Is Zip a MapReduce type? - vp_arth
  • @vp_arth, an interesting analogy. Maybe. It synchronizes two sequences and returns element by element to the function. - Qwertiy

I will add already existing options. If you are not familiar with delegates, then you can write 3 methods, each method considers a specific function and displays the result, but I advise you to pay attention to delegates.

Create an array of delegates and walk the nested loop

 Func<double, double>[] functions = { Math.Sin, Math.Cos, Math.Tan }; string[] funcName = { "Синус", "Косинус", "Тангенс" }; for (int i = 0; i < functions.Length; i++) for (double theta = 0.1; theta <= 1.0; theta = theta + 0.1) Console.WriteLine("{0} угла {1} равен {2}", funcName[i], theta, Math.Round(functions[i](theta),2)) ; 

    It is possible to implement the solution of your problem in this way. Using only one for loop:

     public static void CalculateAndPrintResultByName(string name) { for (double theta = 0.1; theta <= 1.0; theta = theta + 0.1) { switch (name) { case "Синус": Console.WriteLine("Синус угла {0} равен {1}", theta, Math.Round(Math.Sin(theta), 2)); break; case "Косинус": Console.WriteLine("Косинус угла {0} равен {1}", theta, Math.Round(Math.Cos(theta), 2)); break; case "Тангенс": Console.WriteLine("Тангенс угла {0} равен {1}", theta, Math.Round(Math.Tan(theta), 2)); break; default: Console.WriteLine("Функция {0} не определена", name); return; } } } 

    Well, the method call:

     CalculateAndPrintResultByName("Синус"); CalculateAndPrintResultByName("Косинус"); CalculateAndPrintResultByName("Тангенс");