powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / перевести из си в яву...
7 сообщений из 7, страница 1 из 1
перевести из си в яву...
    #34479101
eugenija
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Вводим любое кол-во цифр, например 574639
Прога находит их сумму 5+7+4+6+3+9


#include "stdio.h"
#include "string.h"
#include "math.h"

int main(int argc, char* argv[])
{
char str[255]={0};
int n=0,N=0;
int sum=0,s=0,d=0;
int k=0;

scanf("%d",&n);
N=n;
do{
k=log(n)/log(10.0);
d=(int)pow(10.0,k);
s=n/d;
n-=s*d;
sum+=s;
}while(n>1);

printf("%d = %d\n",N,sum);
sprintf(str,"%d",N);
sum=0;
for(int i=0;i<strlen(str);i++)
{
sum+=str -0x30;
}
printf("%d = %d\n",N,sum);

return 0;
}
...
Рейтинг: 0 / 0
перевести из си в яву...
    #34479108
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
eugenija
scanf("%d",&n);
N=n;
do{
k=log(n)/log(10.0);
d=(int)pow(10.0,k);
s=n/d;
n-=s*d;
sum+=s;
}while(n>1);


Не пойму, зачем этот кусок кода нужен. Очевидно вы использовали математически точный, но абсолютно непрактичный алгоритм. Попробуйте обойтись без логарифмирования. Разряды числа в десятичной системе можно получить путём строковых операций над вводимыми пользователем данными.

P.S. Перевод на Java вообще-то займет считанные секунды...
...
Рейтинг: 0 / 0
перевести из си в яву...
    #34479120
y3u
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
не знаю что там на сях написано, вот такая прога пойдет? джава 5+, там автобоксинг... без него переделать если что - секунда...
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
     public   static   void  main(String[] args) {
         long  result =  0 ;
         for  ( int  i =  0 , j = args[ 0 ].length(); i < j; i++) {
             char  c = args[ 0 ].charAt(i);
             if  (Character.isDigit(c)) {
                result += Integer.valueOf(String.valueOf(c));
            }    
        }
        System.out.println(result);
    }
...
Рейтинг: 0 / 0
перевести из си в яву...
    #34479145
eugenija
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
y3uне знаю что там на сях написано, вот такая прога пойдет? джава 5+, там автобоксинг... без него переделать если что - секунда...
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
     public   static   void  main(String[] args) {
         long  result =  0 ;
         for  ( int  i =  0 , j = args[ 0 ].length(); i < j; i++) {
             char  c = args[ 0 ].charAt(i);
             if  (Character.isDigit(c)) {
                result += Integer.valueOf(String.valueOf(c));
            }    
        }
        System.out.println(result);
    }



Спасибо. Очень интересное решение
а как вы вводите строку чисел?? это переменная с как я поняла?
...
Рейтинг: 0 / 0
перевести из си в яву...
    #34479212
LINUXER
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
eugenija
Спасибо. Очень интересное решение
а как вы вводите строку чисел?? это переменная с как я поняла?
args[] оно как в сях *argv - аргументы командной строки
...
Рейтинг: 0 / 0
перевести из си в яву...
    #34480086
Зашедший
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
eugenijaа как вы вводите строку чисел?? это переменная с как я поняла?
Переменная с - одиночный символ из строки. Строка - первый аргумент командной строки, args[0].
...
Рейтинг: 0 / 0
Период между сообщениями больше года.
перевести из си в яву...
    #37809227
Meison
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Помогите перевести программу с языка C на Java. Очень надо - курсовая горит :(
описание логики работы в комментариях и во здесь , правда на английском :(
сам код программы:
Код: plaintext
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.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
/*

This source code accompanies the article, "Using The Golay Error Detection And
Correction Code", by Hank Wallace. This program demonstrates use of the Golay
code.

   Usage: G DATA Encode/Correct/Verify/Test

     where DATA is the data to be encoded, codeword to be corrected,
     or codeword to be checked for errors. DATA is hexadecimal.

   Examples:

     G 555 E      encodes information value 555 and prints a codeword
     G ABC123 C   corrects codeword ABC123
     G ABC123 V   checks codeword ABC123 for errors
     G ABC123 T   tests routines, ABC123 is a dummy parameter

This program may be freely incorporated into your programs as needed. It
compiles under Borland's Turbo C 2.0. No warranty of any kind is granted.

*/

#include "stdio.h"
#include "conio.h"

#define POLY  0xAE3  /* or use the other polynomial, 0xC75 */

/* ====================================================== */

unsigned long golay(unsigned long cw)
/* This function calculates [23,12] Golay codewords.
   The format of the returned longint is
   [checkbits(11),data(12)]. */
{
  int i;
  unsigned long c;
  cw&=0xfffl;
  c=cw; /* save original codeword */
  for (i=1; i<=12; i++)  /* examine each data bit */
    {
      if (cw & 1)        /* test data bit */
        cw^=POLY;        /* XOR polynomial */
      cw>>=1;            /* shift intermediate result */
    }
  return((cw<<12)|c);    /* assemble codeword */
}

/* ====================================================== */

int parity(unsigned long cw)
/* This function checks the overall parity of codeword cw.
   If parity is even, 0 is returned, else 1. */
{
  unsigned char p;

  /* XOR the bytes of the codeword */
  p=*(unsigned char*)&cw;
  p^=*((unsigned char*)&cw+1);
  p^=*((unsigned char*)&cw+2);

  /* XOR the halves of the intermediate result */
  p=p ^ (p>>4);
  p=p ^ (p>>2);
  p=p ^ (p>>1);

  /* return the parity result */
  return(p & 1);
}

/* ====================================================== */

unsigned long syndrome(unsigned long cw)
/* This function calculates and returns the syndrome
   of a [23,12] Golay codeword. */
{
  int i;
  cw&=0x7fffffl;
  for (i=1; i<=12; i++)  /* examine each data bit */
    {
      if (cw & 1)        /* test data bit */
        cw^=POLY;        /* XOR polynomial */
      cw>>=1;            /* shift intermediate result */
    }
  return(cw<<12);        /* value pairs with upper bits of cw */
}

/* ====================================================== */

int weight(unsigned long cw)
/* This function calculates the weight of
   23 bit codeword cw. */
{
  int bits,k;

  /* nibble weight table */
  const char wgt[16] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};

  bits=0; /* bit counter */
  k=0;
  /* do all bits, six nibbles max */
  while ((k<6) && (cw))
    {
      bits=bits+wgt[cw & 0xf];
      cw>>=4;
      k++;
    }

  return(bits);
}

/* ====================================================== */

unsigned long rotate_left(unsigned long cw, int n)
/* This function rotates 23 bit codeword cw left by n bits. */
{
  int i;

  if (n != 0)
    {
      for (i=1; i<=n; i++)
        {
          if ((cw & 0x400000l) != 0)
            cw=(cw << 1) | 1;
          else
            cw<<=1;
        }
    }

  return(cw & 0x7fffffl);
}

/* ====================================================== */

unsigned long rotate_right(unsigned long cw, int n)
/* This function rotates 23 bit codeword cw right by n bits. */
{
  int i;

  if (n != 0)
    {
      for (i=1; i<=n; i++)
        {
          if ((cw & 1) != 0)
            cw=(cw >> 1) | 0x400000l;
          else
            cw>>=1;
        }
    }

  return(cw & 0x7fffffl);
}

/* ====================================================== */

unsigned long correct(unsigned long cw, int *errs)
/* This function corrects Golay [23,12] codeword cw, returning the
   corrected codeword. This function will produce the corrected codeword
   for three or fewer errors. It will produce some other valid Golay
   codeword for four or more errors, possibly not the intended
   one. *errs is set to the number of bit errors corrected. */
{
  unsigned char
    w;                /* current syndrome limit weight, 2 or 3 */
  unsigned long
    mask;             /* mask for bit flipping */
  int
    i,j;              /* index */
  unsigned long
    s,                /* calculated syndrome */
    cwsaver;          /* saves initial value of cw */

  cwsaver=cw;         /* save */
  *errs=0;
  w=3;                /* initial syndrome weight threshold */
  j=-1;               /* -1 = no trial bit flipping on first pass */
  mask=1;
  while (j<23) /* flip each trial bit */
    {
      if (j != -1) /* toggle a trial bit */
        {
          if (j>0) /* restore last trial bit */
            {
              cw=cwsaver ^ mask;
              mask+=mask; /* point to next bit */
            }
          cw=cwsaver ^ mask; /* flip next trial bit */
          w=2; /* lower the threshold while bit diddling */
        }

      s=syndrome(cw); /* look for errors */
      if (s) /* errors exist */
        {
          for (i=0; i<23; i++) /* check syndrome of each cyclic shift */
            {
              if ((*errs=weight(s)) <= w) /* syndrome matches error pattern */
                {
                  cw=cw ^ s;              /* remove errors */
                  cw=rotate_right(cw,i);  /* unrotate data */
                  return(s=cw);
                }
              else
                {
                  cw=rotate_left(cw,1);   /* rotate to next pattern */
                  s=syndrome(cw);         /* calc new syndrome */
                }
            }
          j++; /* toggle next trial bit */
        }
      else
        return(cw); /* return corrected codeword */
    }

  return(cwsaver); /* return original if no corrections */
} /* correct */

/* ====================================================== */

int decode(int correct_mode, int *errs, unsigned long *cw)
/* This function decodes codeword *cw in one of two modes. If correct_mode
   is nonzero, error correction is attempted, with *errs set to the number of
   bits corrected, and returning 0 if no errors exist, or 1 if parity errors
   exist. If correct_mode is zero, error detection is performed on *cw,
   returning 0 if no errors exist, 1 if an overall parity error exists, and
   2 if a codeword error exists. */
{
  unsigned long parity_bit;

  if (correct_mode)               /* correct errors */
    {
      parity_bit=*cw & 0x800000l; /* save parity bit */
      *cw&=~0x800000l;            /* remove parity bit for correction */

      *cw=correct(*cw, errs);     /* correct up to three bits */
      *cw|=parity_bit;            /* restore parity bit */

      /* check for 4 bit errors */
      if (parity(*cw))            /* odd parity is an error */
        return(1);
      return(0); /* no errors */
    }
  else /* detect errors only */
    {
      *errs=0;
      if (parity(*cw)) /* odd parity is an error */
        {
          *errs=1;
          return(1);
        }
      if (syndrome(*cw))
        {
          *errs=1;
          return(2);
        }
      else
        return(0); /* no errors */
    }
} /* decode */

/* ====================================================== */

void golay_test(void)
/* This function tests the Golay routines for detection and correction
   of various patterns of error_limit bit errors. The error_mask cycles
   over all possible values, and error_limit selects the maximum number
   of induced errors. */
{
  unsigned long
    error_mask,         /* bitwise mask for inducing errors */
    trashed_codeword,   /* the codeword for trial correction */
    virgin_codeword;    /* the original codeword without errors */
  unsigned char
    pass=1,             /* assume test passes */
    error_limit=3;      /* select number of induced bit errors here */
  int
    error_count;        /* receives number of errors corrected */

  virgin_codeword=golay(0x555); /* make a test codeword */
  if (parity(virgin_codeword))
    virgin_codeword^=0x800000l;
  for (error_mask=0; error_mask<0x800000l; error_mask++)
    {
      /* filter the mask for the selected number of bit errors */
      if (weight(error_mask) <= error_limit) /* you can make this faster! */
        {
          trashed_codeword=virgin_codeword ^ error_mask; /* induce bit errors */

          decode(1,&error_count,&trashed_codeword); /* try to correct bit errors */

          if (trashed_codeword ^ virgin_codeword)
            {
              printf("Unable to correct %d errors induced with error mask = 0x%lX\n",
                weight(error_mask),error_mask);
              pass=0;
            }

          if (kbhit()) /* look for user input */
            {
              if (getch() == 27) return; /* escape exits */

              /* other key prints status */
              printf("Current test count = %ld of %ld\n",error_mask,0x800000l);
            }
        }
    }
  printf("Golay test %s!\n",pass?"PASSED":"FAILED");
}

/* ====================================================== */

void main(int argument_count, char *argument[])
{
  int i,j;
  unsigned long l,g;
  const char *errmsg = "Usage: G DATA Encode/Correct/Verify/Test\n\n"
             "  where DATA is the data to be encoded, codeword to be corrected,\n"
             "  or codeword to be checked for errors. DATA is hexadecimal.\n\n"
             "Examples:\n\n"
             "  G 555 E      encodes information value 555 and prints a codeword\n"
             "  G ABC123 C   corrects codeword ABC123\n"
             "  G ABC123 V   checks codeword ABC123 for errors\n"
             "  G ABC123 T   tests routines, ABC123 is a dummy parameter\n\n";

  if (argument_count != 3)
    {
      printf(errmsg);
      exit(0);
    }

  if (sscanf(argument[1],"%lx",&l) != 1)
    {
      printf(errmsg);
      exit(0);
    }

  switch (toupper(*argument[2]))
    {
      case 'E': /* encode */
        l&=0xfff;
        l=golay(l);
        if (parity(l)) l^=0x800000l;
        printf("Codeword = %lX\n",l);
        break;

      case 'V': /* verify */
        if (decode(0,&i,&l))
          printf("Codeword %lX is not a Golay codeword.\n",l);
        else
          printf("Codeword %lX is a Golay codeword.\n",l);
        break;

      case 'C': /* correct */
        g=l; /* save initial codeword */
        j=decode(1,&i,&l);
        if ((j) && (i))
          printf("Codeword %lX had %d bits corrected,\n"
                 "resulting in codeword %lX with a parity error.\n",g,i,l);
        else
          if ((j == 0) && (i))
            printf("Codeword %lX had %d bits corrected, resulting in codeword %lX.\n",g,i,l);
          else
            if ((j) && (i == 0))
              printf("Codeword %lX has a parity error. No bits were corrected.\n",g);
            else
              if ((j == 0) && (i == 0))
                printf("Codeword %lX does not require correction.\n",g);
        break;

      case 'T': /* test */
        printf("Press SPACE for status, ESC to exit test...\n");
        golay_test();
        break;

      default:
        printf(errmsg);
        exit(0);
    }
}

/* end of G.C */


Программа реализует помехоустойчивое кодирование по Голею[24,12,8].
Идеальный вариант: программа такого вида , но увы исходников автор не выложил ;(
Помоги пожалуйста, перевести программу..
p.s. в аттач приложил исходники и откомпилированную программу на C, которую собственно и хотелось перевести ;)
...
Рейтинг: 0 / 0
7 сообщений из 7, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / перевести из си в яву...
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]