溫馨提示×

C++程序中如何轉換ushort與其他類型

c++
小樊
154
2024-08-27 12:05:22
欄目: 編程語言

在 C++ 中,unsigned short(通常簡寫為 ushort)是一種無符號整數類型,用于存儲非負整數

  1. 轉換為 int: 由于 int 可以容納任何 unsigned short 的值,因此可以直接將 unsigned short 值賦給 int 變量。
#include<iostream>

int main() {
    unsigned short ushortValue = 42;
    int intValue = ushortValue;

    std::cout << "ushort value: " << ushortValue<< std::endl;
    std::cout << "int value: "<< intValue<< std::endl;

    return 0;
}
  1. 轉換為 float 或 double: 要將 unsigned short 轉換為浮點數,可以使用靜態類型轉換(static_cast)。
#include<iostream>

int main() {
    unsigned short ushortValue = 42;
    float floatValue = static_cast<float>(ushortValue);
    double doubleValue = static_cast<double>(ushortValue);

    std::cout << "ushort value: " << ushortValue<< std::endl;
    std::cout << "float value: "<< floatValue<< std::endl;
    std::cout << "double value: "<< doubleValue<< std::endl;

    return 0;
}
  1. 轉換為字符串: 要將 unsigned short 轉換為字符串,可以使用 std::to_string() 函數。
#include<iostream>
#include<string>

int main() {
    unsigned short ushortValue = 42;
    std::string stringValue = std::to_string(ushortValue);

    std::cout << "ushort value: " << ushortValue<< std::endl;
    std::cout << "string value: "<< stringValue<< std::endl;

    return 0;
}

請注意,這些示例僅適用于 C++11 及更高版本。如果你使用的是較舊的 C++ 標準,可能需要使用其他方法進行類型轉換。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女