You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中使用read_line读取浮点数报错:expected struct `String`, found `f64` 求助

Fixing Rust Temperature Converter: Reading Floating-Point Input Correctly

Hey there! Let's get your temperature conversion program working smoothly. The error you're hitting makes total sense—read_line is designed to read text input into a String, not directly into a numeric type like f64. Here's how to fix it step by step:

Why the Error Happens

.read_line(&mut fahrenheit) | ^^^^^^^^^^^^^^^ expected struct String , found f64

The read_line method requires a mutable reference to a String because it reads the entire line of input (including the newline character) as text. You can't pass an f64 directly here—Rust's strict type system won't allow it.

Step-by-Step Fix

  1. Read input into a String first: Declare a mutable String variable to capture the user's input.
  2. Clean up the input: Use trim() to remove any leading/trailing whitespace (like the newline character from pressing Enter).
  3. Convert the String to f64: Use the parse() method to turn the cleaned text into a floating-point number. We'll add error handling here in case the user enters something that isn't a valid number.
  4. Keep your conversion logic: Your temperature conversion logic looks solid—we'll keep that core functionality intact.

Modified Working Code

use std::io; // Don't forget to import the io module!

fn main(){
    println!("Enter fahrenheit: ");
    
    // Step 1: Create a mutable String to hold input
    let mut input = String::new();
    
    // Step 2: Read input into the String
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");
    
    // Step 3: Convert String to f64, with error handling
    let fahrenheit: f64 = input.trim()
        .parse()
        .expect("Please enter a valid number");
    
    // Step 4: Run conversion and print result
    let temp_convert = fahrenheit_to_celsius(fahrenheit);
    println!("Converted to Celsius: {temp_convert}");
}

// Renamed to follow Rust's snake_case convention for idiomatic code
fn fahrenheit_to_celsius(x: f64) -> f64{
    (x - 32.0) * 5.0 / 9.0
}

Extra Notes

  • I added use std::io; at the top—your original code was missing this import, which would have caused another error once the type mismatch was fixed!
  • Renamed functions and variables to follow Rust's standard snake_case convention (this makes your code feel more natural to other Rust developers).
  • The parse() method returns a Result, so using expect() gives a helpful error message if the user enters something non-numeric (like "abc" instead of 72). For more robust handling, you could use a match expression to prompt the user again instead of panicking.

内容的提问来源于stack exchange,提问作者De.Shaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:02:37