flutter (In Dart语言)计算作为参数输入的数字的阶乘值并返回它编写返回的方法

oo7oh9g9  于 2023-10-22  发布在  Flutter
关注(0)|答案(5)|浏览(109)

(In Dart语言)计算作为参数输入的数字的阶乘值并返回它编写返回的方法
我想学扑翼,我擅长函数,但我做不到。我想要的是把输入的数字向后相乘。例如,如果输入的数字是3,则过程如下:321将给予答案6。

dphi5xsq

dphi5xsq1#

第一种方法(迭代):

int factorial(int n) {
    if (n < 0) {
      throw ArgumentError('The input number should be a non-negative integer.');
    }
    if (n == 0) return 1;
    int result = 1;
    for (var i = n; i > 0; i--) {
      result *= i;
    }
    return result;
  }

第二种方法(递归):

int factorialRec(int n) {
    if (n < 0) {
      throw ArgumentError('The input number should be a non-negative integer.');
    }
    if (n == 0 || n == 1) return 1;
    return n * factorial(n - 1);
  }
dm7nw8vv

dm7nw8vv2#

这里的方法:

int calculateFactorial(int n) {
  if (n == 0) {
    return 1;
  }

  int factorial = 1;
  for (int i = n; i >= 1; i--) {
    factorial *= i;
  }
  return factorial;
}

下面是完整的app代码:

import 'package:flutter/material.dart';

int calculateFactorial(int n) {
  if (n == 0) {
    return 1;
  }

  int factorial = 1;
  for (int i = n; i >= 1; i--) {
    factorial *= i;
  }
  return factorial;
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController();
  String result = '';
  String errorText = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Factorial Calculator'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextField(
                  controller: _controller,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    labelText: 'Enter a positive integer',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    errorText: errorText,
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: () {
                  int number = int.tryParse(_controller.text) ?? 0;
                  if (number >= 0) {
                    int factorial = calculateFactorial(number);
                    setState(() {
                      result = 'Factorial of $number is $factorial';
                      errorText = '';
                    });
                  } else {
                    setState(() {
                      result = '';
                      errorText = 'Please enter a positive integer.';
                    });
                  }
                },
                child: const Text('Calculate Factorial'),
              ),
              if (result.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(
                    result,
                    style: const TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

希望这能回答你的问题。

drkbr07n

drkbr07n3#

您可以使用递归概念找到方法的阶乘,这有助于您编写最少的代码

int factorial(int n) {
  if (n < 0) {
    throw Exception("Factorial isn't defined for negative numbers.");
  }
  return n == 0 ? 1 : n * factorial(n - 1);
}
ogq8wdun

ogq8wdun4#

使用最近发布的模式匹配:

int factorial(int n) => switch (n) {
  < 0 => throw ArgumentError('n must be positive'),
  0 => 1,
  _ => n * factorial(n - 1),
};
wz3gfoph

wz3gfoph5#

这是你的方法,根据它可能是你可能会得到的结果。

int calculateFactorial(int n) {
  if (n < 0) {
    throw ArgumentError("Factorial is not defined for negative numbers");
  }
  if (n == 0 || n == 1) {
    return 1;
  }

  int factorial = 1;
  for (int i = 2; i <= n; i++) {
    factorial *= i;
  }

  return factorial;
}

void main() {
  int number = 5; // Change this to any number for which you want to calculate the factorial.
  try {
    int result = calculateFactorial(number);
    print("Factorial of $number is $result");
  } catch (e) {
    print(e);
  }
}

相关问题