String to integer

I created a program that converts the numbers entered into a string into an integer like atoi, but it gives the wrong output.

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
void main(void)
{
 static int sum;
 int i,x,y,z;
 char string[10];
 printf("Enter a string:\n");
 gets(string);
 x=strlen(string);
 for(i=0; ;i++)
 {
  if(string[i]=='\0')
  {
   break;
  }
  y=pow(10,i);
  z=string[x-i+1]*y;
  sum+=z;
 }
 printf("%d",sum);
 getch();
}
+3
source share
3 answers

Ok Here is a brief overview of your code. Inline comments.

#include<stdio.h>

Leave a space between #includeand <stdio.h>.

#include<conio.h>

This is a custom Windows-only title that you do not need. Do not turn it on.

#include<math.h>
#include<string.h>

Use space again when including headers.

void main(void)

Although this is legal, a signature is more common int main(int argc, char* argv[])as a signature for the main function. I would suggest that you use this signature.

 {
     static int sum;

? sum, ? , .

 int i,x,y,z;
 char string[10];

. . , , , , , .

printf("Enter a string:\n");
gets(string);

. !!! get !. . fgets , , . , - .

x=strlen(string);

x. , len. ( ) , .

for(i=0; ;i++)
{
  if(string[i]=='\0')
  {
     break;
  }

for-loop; for(i = 0; string[i]!='\0'; i++).

  y=pow(10,i);
  z=string[x-i+1]*y;

: , pow.

  sum+=z;
 }
 printf("%d",sum);

Ok. , "% d\n".

 getch();

. :

#ifdef _WIN32
    system("pause");
#endif

, . , script . - ( Windows) script. , Windows, .

}

-, int, , return 0; .

+5

int 0, 1, 2, ... 9.

char '0', '1', '2', ... '9'. , . ASCII, '0' == 48.

char int; '0', :

z = (string[x-i+1] - '0') * y;


Horner

, pow, .

( ^ -xor):

8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
        = (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9

, . , 10 .

:

step   result  digit  result*10+digit
   1   init=0      8                8
   2        8      6               86
   3       86      7              867
   4      867      5             8675
   5     8675      3            86753
   6    86753      0           867530
   7   867530      9          8675309=final

, .

.

+5

it should be:

z=(string[x-(i+1)]-'0')*y;
+2
source

Source: https://habr.com/ru/post/1754114/


All Articles