w3resource

Rust: Print Latitude and Longitude separately

Rust Variables and Data Types: Exercise-7 with Solution

Write a Rust program that defines a tuple of coordinates representing latitude and longitude. Print each tuple element separately.

Sample Solution:

Rust Code:

fn main() {
    // Define a tuple named 'coordinates' containing latitude and longitude
    let coordinates: (f64, f64) = (40.7128, -74.0060);

    // Access and print the latitude
    println!("Latitude: {}", coordinates.0);

    // Access and print the longitude
    println!("Longitude: {}", coordinates.1);
}

Output:

Latitude: 40.7128
Longitude: -74.006

Explanation:

Here's a brief explanation of the above Rust code:

  • 'fn main() { ... }': This is the entry point of the program.
  • 'let coordinates: (f64, f64) = (40.7128, -74.0060);': This line defines a tuple named 'coordinates' containing latitude and longitude values. The tuple type is explicitly specified as '(f64, f64)' indicating that it contains two floating-point numbers.
  • 'println!("Latitude: {}", coordinates.0);': This line prints the first element of the tuple, representing the latitude.
  • 'println!("Longitude: {}", coordinates.1);': This line prints the second element of the tuple, representing the longitude.

Rust Code Editor:

Previous: Rust Program: Convert Celsius to Fahrenheit.
Next: Rust Program: Iterate over array and print elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/basic/rust-variables-and-data-types-exercise-7.php