Вопрос задан 01.12.2023 в 12:36. Предмет Информатика. Спрашивает Новикова Анастасия.

- Создать возвращаемый метод который будет принимать 2 входящих параметра - возраст человека и

температуру на улице, и возвращать результат в виде строки. - Алгоритм метода должен работать следующим образом: - если возраст человека от 20 до 45 лет и температура на улице от -20 до 30 градусов, то возвращаемый результат - "Можно идти гулять";п - eсли же человеку меньше 20 лет и температура на улице в диапазоне от 0 до 28 градусов, то результат снова - "Можно идти гулять"; - а если человеку больше 45 лет, то результат "Можно идти гулять" формируется только тогда когда на улице температура в диапазоне от -10 до 25 градусов; - В остальных случаях метод должен возвращать результат - "Оставайтесь дома"; - В методе main вызвать написанный метод 5 раз с различными входными данными (аргументами) и распечатать результат в консоль. ДЗ на сообразительность: - Написать метод в котором генерируется случайный возраст public static int generateRandomAge(){........} - При вызове метода, который формирует результат "можно ли идти гулять" использовать генерирование случайного возраста с помощью метода "generateRandomAge"
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Тищенко Мирослав.

C++:

#include <iostream>

#include <windows.h>

#include <time.h>

using namespace std;

struct Person

{  

   string canGoOutside(int age, float temperature)

   {

       if(age >= 20 && age <= 45 && temperature >= -20 && temperature <= 30)

           return "Можно идти гулять";

       else if(age < 20 && temperature >= 0 && temperature <= 28)

           return "Можно идти гулять";

       else if(age > 45 && temperature >= -10 && temperature <= 25)

           return "Можно идти гулять";

       else

           return "Отсавайтесь дома";

   }

   int generateRandomAge(int min, int max){

       return min + rand() % (max + 1 - min);

   }

};

int main()

{

   SetConsoleCP(65001);

   SetConsoleOutputCP(65001);

   srand(time(NULL));

   Person Adolf;

   cout << Adolf.canGoOutside(15, 15) << endl;

   cout << Adolf.canGoOutside(73,5) << endl;

   cout << Adolf.canGoOutside(36, -10) << endl;

   cout << Adolf.canGoOutside(19, -25) << endl;

   cout << endl;

   

   cout << Adolf.canGoOutside(Adolf.generateRandomAge(5, 65), -5) << endl;

   cout << Adolf.canGoOutside(Adolf.generateRandomAge(5, 65), 10) << endl;

   cout << Adolf.canGoOutside(Adolf.generateRandomAge(5, 65), 0) << endl;

   cout << Adolf.canGoOutside(Adolf.generateRandomAge(5, 65), 40) << endl;

   return 0;

}

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Creating a Method to Determine if You Can Go for a Walk

To create a method that takes two input parameters (age and outdoor temperature) and returns a result as a string, follow these steps:

1. Define the method with the appropriate return type and parameter types. In this case, the method should return a string and accept an integer for age and another integer for outdoor temperature. 2. Implement the algorithm inside the method to determine the result based on the given conditions. 3. Use conditional statements (if-else) to check the age and temperature ranges and return the corresponding result as a string. 4. In the `main` method, call the created method five times with different input values and print the result to the console.

Here's an example implementation in Java:

```java public class WalkDecision { public static void main(String[] args) { // Call the method with different input values and print the result System.out.println(goForWalk(25, 15)); System.out.println(goForWalk(18, 25)); System.out.println(goForWalk(50, 20)); System.out.println(goForWalk(30, 35)); System.out.println(goForWalk(15, 10)); }

public static String goForWalk(int age, int temperature) { if (age >= 20 && age <= 45 && temperature >= -20 && temperature <= 30) { return "You can go for a walk."; } else if (age < 20 && temperature >= 0 && temperature <= 28) { return "You can go for a walk."; } else if (age > 45 && temperature >= -10 && temperature <= 25) { return "You can go for a walk."; } else { return "Stay at home."; } } } ```

In this example, the `goForWalk` method takes the age and temperature as input parameters and returns a string based on the given conditions. The `main` method calls this method five times with different input values and prints the result to the console.

Generating a Random Age

To generate a random age, you can create a separate method called `generateRandomAge` that returns an integer. Here's an example implementation:

```java import java.util.Random;

public class WalkDecision { public static void main(String[] args) { // Call the method with a randomly generated age and print the result int randomAge = generateRandomAge(); int temperature = 20; // Set the temperature to a specific value System.out.println(goForWalk(randomAge, temperature)); }

public static int generateRandomAge() { Random random = new Random(); int minAge = 1; int maxAge = 100; return random.nextInt(maxAge - minAge + 1) + minAge; }

public static String goForWalk(int age, int temperature) { // Method implementation remains the same as before } } ```

In this example, the `generateRandomAge` method uses the `Random` class to generate a random integer between 1 and 100 (inclusive). The generated age is then passed as an argument to the `goForWalk` method, along with a specific temperature value. The result is printed to the console.

Please note that the `generateRandomAge` method can be called multiple times to generate different random ages.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос