Компиляция кода программы на С#
Новичок в С#, конвертировал код простой программы своей с С++ на это чудесный язык программирования. Получился файл программы GlobalMembers.cs и файла класса. Добавлял в проект в VS2008, не могу оттранслировать, связи никакой. Задача вообще простая, сделать эту программу в консольном виде (чтоб легко запускать в онлайн IDE), что нужно поменять (менял название классов по типу структуры Console program, не получается ничего, множество ошибок). Помогите пожалуйста запустить ее в С Шарп виде.
GlobalMembers.cs:
using System;
public static class GlobalMembers
{
internal static void Main()
{
setlocale(0,"");
const int n = 3;
int i;
int[] x = new int[n];
int[] y = new int[n];
int a = 0;
int b;
double[] z = new double[n];
double max;
for (i = 0; i < n; i++)
{
Console.Write("Введите [");
Console.Write(i);
Console.Write("] элемент массива X: ");
x[i] = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
}
for (i = 0; i < n; i++)
{
Console.Write("Введите [");
Console.Write(i);
Console.Write("] элемент массива Y: ");
y[i] = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
if (y[i] > 5)
{
z[i] = (2.5 * Math.Pow(y[i],1.0 / 3.0)) - 6.8 * y[i] + 0.8;
}
else
{
z[i] = Math.Exp(Math.Abs(y[i] - 2.0)) - Math.Sqrt(Math.Abs(y[i] + 5.0));
}
}
Console.Write("Массив X: ");
Console.Write("\n");
Console.Write("\n");
for (i = 0; i < n; i++)
{
Console.Write(x[i]);
Console.Write(" ");
}
Console.Write("\n");
Console.Write("\n");
Console.Write("Массив Y: ");
Console.Write("\n");
Console.Write("\n");
for (i = 0; i < n; i++)
{
Console.Write(y[i]);
Console.Write(" ");
}
Console.Write("\n");
Console.Write("\n");
Console.Write("Массив Z: ");
Console.Write("\n");
Console.Write("\n");
for (i = 0; i < n; i++)
{
Console.Write(z[i]);
Console.Write(" ");
}
max = z[0];
for (i = 0; i < 5; i++)
{
if (z[i] > 0 && i == 0)
{
if (z[i + 1] < 0 && max < z[i])
{
max = z[i];
a = i;
b = 1;
}
}
else
{
if (z[i - 1] < 0 && z[i + 1] < 0 && max < z[i])
{
max = z[i];
a = i;
b = 1;
}
}
}
if (b == 1)
{
Console.Write("\n");
Console.Write("\n");
Console.Write("max элемент под номером [");
Console.Write(a);
Console.Write("] = ");
Console.Write(max);
Console.Write("\n");
Console.Write("\n");
}
else
{
Console.Write("\n");
Console.Write("\n");
Console.Write("Чисел окруженных отрицательными элементами не найдено!");
Console.Write("\n");
Console.Write("\n");
}
system("pause");
}
}
======================================================== ConsoleInput.cs:
internal static class ConsoleInput
{
private static bool goodLastRead = false;
public static bool LastReadWasGood
{
get
{
return goodLastRead;
}
}
public static string ReadToWhiteSpace(bool skipLeadingWhiteSpace)
{
string input = "";
char nextChar;
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
//accumulate leading white space if skipLeadingWhiteSpace is false:
if (!skipLeadingWhiteSpace)
input += nextChar;
}
//the first non white space character:
input += nextChar;
//accumulate characters until white space is reached:
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
}
goodLastRead = input.Length > 0;
return input;
}
public static string ScanfRead(string unwantedSequence = null, int maxFieldLength = -1)
{
string input = "";
char nextChar;
if (unwantedSequence != null)
{
nextChar = '\0';
for (int charIndex = 0; charIndex < unwantedSequence.Length; charIndex++)
{
if (char.IsWhiteSpace(unwantedSequence[charIndex]))
{
//ignore all subsequent white space:
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
}
}
else
{
//ensure each character matches the expected character in the sequence:
nextChar = (char)System.Console.Read();
if (nextChar != unwantedSequence[charIndex])
return null;
}
}
input = nextChar.ToString();
if (maxFieldLength == 1)
return input;
}
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
if (maxFieldLength == input.Length)
return input;
}
return input;
}
}
Ответы (1 шт):
Поправил несколько ошибок
public static class GlobalMembers
{
internal static void Main()
{
const int n = 3;
int i;
int[] x = new int[n];
int[] y = new int[n];
int a = 0;
int b = 0;
double[] z = new double[n];
double max;
for (i = 0; i < n; i++)
{
Console.Write("Введите [");
Console.Write(i);
Console.Write("] элемент массива X: ");
x[i] = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
}
for (i = 0; i < n; i++)
{
Console.Write("Введите [");
Console.Write(i);
Console.Write("] элемент массива Y: ");
y[i] = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
if (y[i] > 5)
{
z[i] = (2.5 * Math.Pow(y[i], 1.0 / 3.0)) - 6.8 * y[i] + 0.8;
}
else
{
z[i] = Math.Exp(Math.Abs(y[i] - 2.0)) - Math.Sqrt(Math.Abs(y[i] + 5.0));
}
}
Console.Write("Массив X: ");
Console.Write("\n");
Console.Write("\n");
for (i = 0; i < n; i++)
{
Console.Write(x[i]);
Console.Write(" ");
}
Console.Write("\n");
Console.Write("\n");
Console.Write("Массив Y: ");
Console.Write("\n");
Console.Write("\n");
for (i = 0; i < n; i++)
{
Console.Write(y[i]);
Console.Write(" ");
}
Console.Write("\n");
Console.Write("\n");
Console.Write("Массив Z: ");
Console.Write("\n");
Console.Write("\n");
for (i = 0; i < n; i++)
{
Console.Write(z[i]);
Console.Write(" ");
}
max = z[0];
for (i = 0; i < n; i++)
{
if (z[i] > 0 && i == 0)
{
if (z[i + 1] < 0 && max < z[i])
{
max = z[i];
a = i;
b = 1;
}
}
else
{
if (z[i - 1] < 0 && z[i + 1] < 0 && max < z[i])
{
max = z[i];
a = i;
b = 1;
}
}
}
if (b == 1)
{
Console.Write("\n");
Console.Write("\n");
Console.Write("max элемент под номером [");
Console.Write(a);
Console.Write("] = ");
Console.Write(max);
Console.Write("\n");
Console.Write("\n");
}
else
{
Console.Write("\n");
Console.Write("\n");
Console.Write("Чисел окруженных отрицательными элементами не найдено!");
Console.Write("\n");
Console.Write("\n");
}
Console.ReadKey();
}
}
Второй класс вообще без изменений собрался
internal static class ConsoleInput
{
private static bool goodLastRead = false;
public static bool LastReadWasGood
{
get
{
return goodLastRead;
}
}
public static string ReadToWhiteSpace(bool skipLeadingWhiteSpace)
{
string input = "";
char nextChar;
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
//accumulate leading white space if skipLeadingWhiteSpace is false:
if (!skipLeadingWhiteSpace)
input += nextChar;
}
//the first non white space character:
input += nextChar;
//accumulate characters until white space is reached:
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
}
goodLastRead = input.Length > 0;
return input;
}
public static string ScanfRead(string unwantedSequence = null, int maxFieldLength = -1)
{
string input = "";
char nextChar;
if (unwantedSequence != null)
{
nextChar = '\0';
for (int charIndex = 0; charIndex < unwantedSequence.Length; charIndex++)
{
if (char.IsWhiteSpace(unwantedSequence[charIndex]))
{
//ignore all subsequent white space:
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
}
}
else
{
//ensure each character matches the expected character in the sequence:
nextChar = (char)System.Console.Read();
if (nextChar != unwantedSequence[charIndex])
return null;
}
}
input = nextChar.ToString();
if (maxFieldLength == 1)
return input;
}
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
if (maxFieldLength == input.Length)
return input;
}
return input;
}
}
Сборка
Build started...
1>------ Build started: Project: LegacyApp, Configuration: Debug Any CPU ------
1> LegacyApp -> C:\Source\LegacyApp\LegacyApp\bin\Debug\LegacyApp.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
Вывод в консоль
Введите [0] элемент массива X: 1
Введите [1] элемент массива X: 2
Введите [2] элемент массива X: 3
Введите [0] элемент массива Y: 4
Введите [1] элемент массива Y: 5
Введите [2] элемент массива Y: 6
Массив X:
1 2 3
Массив Y:
4 5 6
Массив Z:
4,38905609893065 16,9232592630193 -35,4571985179197
Чисел окруженных отрицательными элементами не найдено!
Принципиально не трогал код, чтобы вы смогли увидеть изменения, которые я сделал, но могу прооптимизировать, если надо.
Я убрал это setlocale(0,""); и это system("pause");, вместо последнего добавил Console.ReadKey();. Вот это int b; заменил на это int b = 0;, и вот это for (i = 0; i < 5; i++) на это for (i = 0; i < n; i++).
