Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/11: Рейтинг темы: голосов - 11, средняя оценка - 5.00
72 / 17 / 2
Регистрация: 29.12.2010
Сообщений: 339

Портирование кода с С# на С++

29.10.2012, 05:51. Показов 2117. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Доброго времени суток!
Помогите, пожалуйста, перевести на с++ такой код(желательно очень близко к оригиналу!!!):
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace ConsoleApplication3
{
 
    class Program
    {
        const double Tier1E = 0.059;
        const double Tier2E = 0.065;
        const double Tier3E = 0.073;
 
        const int LevelCh1E = 700;
        const int LevelCh2E = 800;
 
        const double Tier1W = 0.0021;
        const double Tier2W = 0.0029;
        const double Tier3W = 0.004;
 
        const int LevelCh1W = 8000;
        const int LevelCh2W = 15000;
 
        const double fee = 4.81;
 
 
        static void Main(string[] args)
        {
            #region Проверка
            if (File.Exists("UTILITY.TXT"))
            {
                //Console.WriteLine("//File exists!");//
            }
            else
            {
                Console.WriteLine("//There is no file there!");
                System.Threading.Thread.Sleep(1000);
            }
            #endregion
            StreamReader sr = new StreamReader("UTILITY.TXT");
            StreamWriter swu = new StreamWriter("UNITS.TXT");
            StreamWriter swc = new StreamWriter("CUSTOMERS.TXT");
            string s;
            string cust_code = "";
            char condition, type;
            double total_cost, coste, costw, total_city = 0;
            int cntw, cnte;
            double realfee;
            int count_screen = 0;
            while ((s = sr.ReadLine()) != null)
            {
                if (count_screen == 0)
                {
                    Console.WriteLine("Customer\tUnits\tUtility\nCode    \tOwned\tCharges\n--------\t------\t-----------");
                }
                count_screen++;
 
                cust_code = s.Substring(0, 8);
                condition = s[9];
                s = s.Remove(0, 11);
                int cnt_units = 0;
                total_cost = 0;
                while (s.Length > 0)
                {
                    #region парсинг
                    type = s[0];
                    s = s.Remove(0, 2);
                    cnte = parse_cnte(s);
                    s = s.Remove(0, s.IndexOf(' ') + 1);
 
                    cntw = parse_cntw(s);
                    if (s.IndexOf(' ') > -1)
                        s = s.Remove(0, s.IndexOf(' ') + 1);
                    else
                        s = "";
                    #endregion
                    #region запись в units
                    coste = count_energy(cnte);
                    costw = count_water(cntw);
                    if (type == 'R')
                        realfee = fee;
                    else
                        realfee = fee * 2;
                    swu.WriteLine(type + " " + Math.Round((costw + coste + realfee), 2).ToString());
                    total_cost += Math.Round((costw + coste + realfee), 2);
                    #endregion
                    cnt_units++;
                }
                swc.WriteLine(cust_code + " " + total_cost);
                total_city += total_cost;
 
                Console.WriteLine(cust_code + "\t   " + cnt_units + "\t$    " + total_cost);
 
                if (count_screen == 20)
                {
                    System.Threading.Thread.Sleep(5000);
                    Console.Clear();
                    count_screen = 0;
                }
            }
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Total City Collected\t" + "$    " + Math.Round(total_city, 2));
 
            swc.Close();
            swu.Close();
            sr.Close();
 
            Console.Read();
        }
 
        static double count_energy(int cnt)
        {
            double res = 0;
            if (cnt <= LevelCh1E)
            {
                res += cnt * Tier1E;
            }
            else if (cnt <= LevelCh2E + LevelCh1E)
            {
                res += LevelCh1E * Tier1E + (cnt - LevelCh1E) * Tier2E;
            }
            else
            {
                res += LevelCh1E * Tier1E + LevelCh2E * Tier2E + (cnt - LevelCh1E - LevelCh2E) * Tier3E;
            }
            return res;
        }
        static double count_water(int cnt)
        {
            double res = 0;
            if (cnt <= LevelCh1W)
            {
                res = cnt * Tier1W;
            }
            else if (cnt <= LevelCh2W)
            {
                res = cnt * Tier2W;
            }
            else
            {
                res = cnt * Tier3W;
            }
            return res;
        }
        static int parse_cnte(string s)
        {
            return int.Parse(s.Substring(0, s.IndexOf(' ') + 1));
        }
        static int parse_cntw(string s)
        {
            if (s.IndexOf(' ') > -1)
            {
                return int.Parse(s.Substring(0, s.IndexOf(' ') + 1));
            }
            else
            {
                return int.Parse(s);
            }
        }
    }
}
Заранее, спасибо

Добавлено через 49 минут
[bump!]
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
29.10.2012, 05:51
Ответы с готовыми решениями:

Портирование кода с c++ на c#
Добрый день! Помогите, пожалуйста, перевести на с# такой код#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;conio.h&gt; ...

Портирование кода
Добрый день, часто вижу, что при портировании кода с ПК версии до мобильной версии, вставляют &quot;костыли&quot; #ifdef...

Портирование кода с C# в Delphi
Здравствуйте. Решил переписать кое что на Delphi. Вроде все правильно переписал, даже для удобства создал свой класс аналог...

1
873 / 771 / 173
Регистрация: 11.01.2012
Сообщений: 1,942
29.10.2012, 08:20
Лучший ответ Сообщение было отмечено Смирняга как решение

Решение

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <iomanip>
//#include <Windows.h>
 
    
        const double Tier1E = 0.059;
        const double Tier2E = 0.065;
        const double Tier3E = 0.073;
 
        const int LevelCh1E = 700;
        const int LevelCh2E = 800;
 
        const double Tier1W = 0.0021;
        const double Tier2W = 0.0029;
        const double Tier3W = 0.004;
 
        const int LevelCh1W = 8000;
        const int LevelCh2W = 15000;
 
        const double fee = 4.81;
 
        double count_energy(int cnt);
        double count_water(int cnt);
        int parse_cnte(std::string& s);
        int parse_cntw( std::string& s );
 
 
        int main()
        {
 
               std::ifstream sr("UTILITY.TXT");
              std::ofstream swu("UNITS.TXT");
              std::ofstream swc("CUSTOMERS.TXT");
            
         //   #region Проверка
            if ( !sr.is_open() )
            {               
                std::cerr << "//There is no file there!";
               // Sleep(1000);
            }
          //  #endregion
            else
            {
          
            std::string s;
            std::string cust_code = "";
            char condition, type;
            double total_cost, coste, costw, total_city = 0;
            int cntw, cnte;
            double realfee;
            int count_screen = 0;
 
            while (getline(sr,s))
            {
                if (count_screen == 0)
                {
                    std::cout << "Customer\tUnits\tUtility\nCode    \tOwned\tCharges\n--------\t------\t-----------\n";
                }
                count_screen++;
 
                cust_code = s.substr(0, 8);
                condition = s[9];
                s.erase(0, 11);
                int cnt_units = 0;
                total_cost = 0;
                while (s.length() > 0)
                {
                  //  #region парсинг
                    type = s[0];
                    s.erase(0, 2);
                    cnte = parse_cnte(s);
                    s.erase(0, s.find(' ') + 1);
 
                    cntw = parse_cntw(s);
                    if (s.find(' ') != std::string::npos)
                        s.erase(0, s.find(' ') + 1);
                    else
                        s = "";
                  //  #endregion
                 //   #region запись в units
                    coste = count_energy(cnte);
                    costw = count_water(cntw);
                    if (type == 'R')
                        realfee = fee;
                    else
                        realfee = fee * 2;
                    swu << type <<  " " << std::fixed << std::setprecision(2) << ( costw + coste + realfee ) << '\n';
                    total_cost +=  ( costw + coste + realfee );
                 //   #endregion
                    cnt_units++;
                }
                swc << cust_code << " " << std::fixed << std::setprecision(2) << total_cost << '\n';
                total_city += total_cost;
 
                std::cout   << cust_code << "\t   "  << cnt_units << "\t$    " << std::fixed << std::setprecision(2) << total_cost << '\n';
 
                if (count_screen == 20)
                {
                   /* Sleep(5000);
                    system ("cls");*/
                    count_screen = 0;
                }
            }
            std::cout << "-----------------------------------\n";
            std::cout << "Total City Collected\t" << "$    "  << std::fixed << std::setprecision(2) << total_city;
            swc.close();
            swu.close();
            sr.close();
            
        }
 
            
            system("pause");
        }
 
        double count_energy(int cnt)
        {
            double res = 0;
            if (cnt <= LevelCh1E)
            {
                res += cnt * Tier1E;
            }
            else if (cnt <= LevelCh2E + LevelCh1E)
            {
                res += LevelCh1E * Tier1E + (cnt - LevelCh1E) * Tier2E;
            }
            else
            {
                res += LevelCh1E * Tier1E + LevelCh2E * Tier2E + (cnt - LevelCh1E - LevelCh2E) * Tier3E;
            }
            return res;
        }
 
         double count_water(int cnt)
        {
            double res = 0;
            if (cnt <= LevelCh1W)
            {
                res = cnt * Tier1W;
            }
            else if (cnt <= LevelCh2W)
            {
                res = cnt * Tier2W;
            }
            else
            {
                res = cnt * Tier3W;
            }
            return res;
        }
 
        int parse_cnte(std::string& s)
        {
            return atoi(( s.substr(0, s.find(' ') + 1)).c_str());
        }
 
       int parse_cntw( std::string& s )
        {
            int iVal;
            if ( s.find(' ') != std::string::npos )
            {
                return atoi(( s.substr(0, s.find(' ') + 1)).c_str());
            }
            else
            {            
                return atoi( s.c_str());
            }
        }
на скринах работа кода С++ и C Sharp
Миниатюры
Портирование кода с С# на С++   Портирование кода с С# на С++  
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
29.10.2012, 08:20
Помогаю со студенческими работами здесь

Портирование кода с с++ на java
Подскажите почему функции дают разный результат? данные uint32_t key={0x699364AA,0x783DD4BB,0x105098CC,0xA85564DD}; unsigned char...

Портирование кода Java в C#
Здравствуйте! Помогите, пожалуйста, разобраться с частью кода. Почти весь код портировал, но выводит 3 ошибки. Не понимаю, как в C#...

Портирование кода с Java на C#
Доброго времени суток, начал портировать код написанный на Java: public static byte stripLeadingZeros(byte in) { int stripCount...

Портирование кода в С++ Builder
Всем привет! Скажите, возможно ли портировать код в Builder. Код был написан в VS ( соответственно и компилятор vs ). Использую из std...

Портирование куска кода (класс BigIntiger) с Java в C#
Доброго времени суток. Как портировать данный код на C#? BigInteger mod = new BigInteger(1,new byte{9,8,7,6,5,4,3,2,1}); ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
YAFU@home — распределённые вычисления для математики. На CPU
Programma_Boinc 20.01.2026
YAFU@home — распределённые вычисления для математики. На CPU YAFU@home — это BOINC-проект, который занимается факторизацией больших чисел и исследованием aliquot-последовательностей. Звучит. . .
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru