找到你要的答案

Q:Function always returns 0 [closed]

Q:函数总是返回0 [关闭]

Function:

int num(char a[]) //将字符串型的数字转化成int 
{
    int  z, x, y;
    z = 0;
    int m = sizeof(a);

    if(m == 1)
        z = a[0] - 48;

    if(m == 2)
    {
        x = a[0] - 48;
        y = a[1] - 48;
        z = x * 10 + y;
    }

    if(m == 3)
    {
        x = a[0] - 48;
        y = a[1] - 48;
        z = a[2] - 48;
        z = x * 100 + y * 10 + z;
    }

eg: char a[3]={2,15};, but num(a) = 0.
I don't know why.

功能:

int num(char a[]) //将字符串型的数字转化成int 
{
    int  z, x, y;
    z = 0;
    int m = sizeof(a);

    if(m == 1)
        z = a[0] - 48;

    if(m == 2)
    {
        x = a[0] - 48;
        y = a[1] - 48;
        z = x * 10 + y;
    }

    if(m == 3)
    {
        x = a[0] - 48;
        y = a[1] - 48;
        z = a[2] - 48;
        z = x * 100 + y * 10 + z;
    }

eg: char a[3]={2,15};, but num(a) = 0.
I don't know why.

answer1: 回答1:

The parameter of the function declared like char a[] is adjusted to type char *. The size of the pointer does not depend on how many elements the array passed as an argument has.

The valid function can look the following way

#include <cstring>

//...

int num( const char a[] )//将字符串型的数字转化成int 
{
    int  z,x,y;

    size_t n = std::strlen( a );

    z = 0;

    if( n == 1 )
        z = a[0] - '0';

    if ( n == 2 )
    {
        x = a[0] - '0';
        y = a[1] - '0';
        z = x * 10 + y;
    }

    if ( n == 3 )
    {
        x = a[0] - '0';
        y = a[1] - '0';
        z = a[2] - '0';
        z = x * 100 + y * 10 + z;
    }
    //...

If you need simply to form a number from a character array you could use standard C function atoi. Or you could write a loop

z = 0;

for ( size_t i = 0; i < 3 && a[i]; i++ ) z = 10 * z + a[i] - '0';

Take into account that if it is the all that the function has to do then you shall include return statement

return z;

将声明的字符的参数调整为char类型*。指针的大小不取决于数组作为参数传递时有多少元素。

有效的功能可以看以下方式

#include <cstring>

//...

int num( const char a[] )//将字符串型的数字转化成int 
{
    int  z,x,y;

    size_t n = std::strlen( a );

    z = 0;

    if( n == 1 )
        z = a[0] - '0';

    if ( n == 2 )
    {
        x = a[0] - '0';
        y = a[1] - '0';
        z = x * 10 + y;
    }

    if ( n == 3 )
    {
        x = a[0] - '0';
        y = a[1] - '0';
        z = a[2] - '0';
        z = x * 100 + y * 10 + z;
    }
    //...

如果你只需要从一个字符数组,你可以使用标准的C函数atoi形成数。或者你可以写一个循环

z = 0;

for ( size_t i = 0; i < 3 && a[i]; i++ ) z = 10 * z + a[i] - '0';

考虑到如果它是函数所要做的全部,那么你应该包含返回语句

return z;
c++