在 Rust 中,将两个整数相除不会打印为十进制数 [英] Dividing two integers doesn't print as a decimal number in Rust

查看:59
本文介绍了在 Rust 中,将两个整数相除不会打印为十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Rust,但是当我打印一个十进制数时,只打印整数部分,而不是小数部分:

I'm learning Rust, but when I print a decimal number, only the integer part is printed, not the decimal part:

fn main(){
    println!("{:.3}", 22/7);
}
// This only show 3

但是当我明确打印十进制数时,它可以正常工作:

but when I print the decimal number explicitly, it works correctly:

fn main(){
    println!("{:.3}", 0.25648);
}
// this print 0.256

推荐答案

就像在 C 和 C++ 中一样,将整数相除会产生另一个整数.试试这个 C++ 程序看看:

Just like in C and C++, dividing integers results in another integer. Try this C++ program to see:

#include <iostream>

using namespace std;

int main()
{
    cout << 22 / 7 << endl;            // 3
    cout << 22.0 / 7.0 << endl;        // 3.14286
}

在 Rust 中类似,您需要将两个数字都指定为浮点数,这是通过在数字的任何位置放置一个小数来实现的.试试上面这个程序的 Rust 等价物:

Similarly in Rust, you need to specify both numbers as floats instead, which is done by putting a decimal anywhere in the number. Try this Rust equivalent of the above program:

fn main() {
    println!("{:.3}", 22 / 7);         // 3
    println!("{:.3}", 22.0 / 7.0);     // 3.143
}

如果您有变量,您可以使用 as 将它们转换为 f32f64,具体取决于您的需要:

If you have variables, you can convert them with as to either f32 or f64, depending on your needs:

fn main() {
    let x = 22;
    println!("{:.3}", x / 7);          // 3
    println!("{:.3}", x as f32 / 7.0); // 3.143
}

这篇关于在 Rust 中,将两个整数相除不会打印为十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆