簡體   English   中英

將數字字符串轉換為整數值

[英]convert the numeric string to integer value

我正在嘗試使用以下代碼將數字字符串轉換為整數值。 輸出始終比原始值小一。 我沒有弄明白我的代碼有什么問題。

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int main(){

    char a[6];

    int i,b;

    scanf("%s",a);

    for(i=strlen(a)-1;i>=0;i--){

        a[i]=a[i]-48;

        b=b+a[i]*pow(10,(strlen(a)-i-1));
    }

    printf("%d",b);

    getch();

    return 0;

}

該問題很可能是未定義的行為,因為您使用了未初始化的變量。

在表達式b=b+... ,使用變量b而不先對其進行初始化。 非靜態局部變量不會被初始化,並且將具有不確定的值。 不進行初始化就使用它們會導致UB。 初始化為零:

int i, b = 0;

用戶還會為數組a輸入許多字符並超出范圍,這也會帶來問題。 您也沒有檢查用戶實際上僅輸入了數字。

您的代碼中幾乎沒有問題。 為了降低UB的風險:

  1. 如果將char[]視為字符串,則其大小應允許容納\\0終止字符。
  2. 如果您的代碼未初始化非靜態局部變量值,則應顯式地執行此操作(變量int b )。
  3. 如果您讀取字符串,請謹慎對待scanf() 溢出導致UB。 使用字段寬度說明符。
  4. 不要混合數據類型( pow()返回值是double )。
  5. 使您的代碼盡可能精簡,並盡量減少實際數學運算,尤其是在內部循環中。 您完全不需要pow()

請根據您的代碼查看注釋:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char a[7];      // extra byte for '\0'
    int i, l, b = 0;//initialize local variable b
    int ten = 1;

    scanf("%6s",a); //should use a field width specifier

    l = strlen(a) - 1;

    for( i=l ; i>=0 ; i--, ten*=10 )
        b += (a[i]-48)*ten; //do as simple math as practical

    printf("%d\n",b);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM