簡體   English   中英

我可以使用 atof 或 atoi 將結果放入 int 變量中嗎?

[英]Can I place the result into an int variable using either atof or atoi?

在 c 中:給定以下代碼

int a;
char word[]=<some string>

有區別嗎?

a = atoi(word) 
a = atof(word)

atoi返回整數類型, atof返回double

因此,在atof場景中,您還將臨時double轉換為int

是的你可以。

但是編譯器會發出警告。 見下文:

在此處輸入圖像描述

它告訴你會發生什么。

所有雙精度或浮點值都將被截斷(不四舍五入)。

請參閱以下代碼:

#include <iostream>
#include <cstdlib>

int main() {
 
    int i1{};
    int i2{};
    int i3{};
    char s1[] = "42";
    char s2[] = "42.1";
    char s3[] = "42.9";

    i1 = std::atof(s1);
    i2 = std::atof(s2);
    i3 = std::atof(s3);

    std::cout << s1 << "\t--> " << i1 << '\n'
        << s2 << "\t--> " << i2 << '\n'
        << s3 << "\t--> " << i3 << '\n';
}

如果你想擺脫警告並且更干凈,你需要添加一個 cast 語句。 如下所示:

#include <iostream>
#include <cstdlib>

int main() {

    int i1{};
    int i2{};
    int i3{};
    char s1[] = "42";
    char s2[] = "42.1";
    char s3[] = "42.9";

    i1 = static_cast<int>(std::atof(s1));
    i2 = static_cast<int>(std::atof(s2));
    i3 = static_cast<int>(std::atof(s3));

    std::cout << s1 << "\t--> " << i1 << '\n'
        << s2 << "\t--> " << i2 << '\n'
        << s3 << "\t--> " << i3 << '\n';
}

不會有編譯器警告:

在此處輸入圖像描述

程序輸出將是:

在此處輸入圖像描述

暫無
暫無

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

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