编写计算阶乘的程序

计算阶乘的程序片段如下:

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

其中的整数n由editText1控件中输入的字符串并通过使用Interger类中的parselnt()函数转换而来。
int n=Integer.parseInt(editText1.getText().toString());
fact变量保存好后的阶乘计算结果,最后显示到textView控件中。
textView1.setText(""+fact);

程序代码:

布局文件的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/LinearLayout1"
    android:orientation="vertical"
    tools:context=".MainActivity"
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:ems="10"
        android:hint="请输入一个整数"
        android:text="">
        <requestFocus/>
    </EditText>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:onClick="calc"
        android:text="计算阶乘" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textView1"
        android:text=""
        android:textAlignment="center" />
</LinearLayout>

活动源程序文件的内容如下:

package com.example.test01;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void calc(View view){
        EditText editText1=(EditText)this.findViewById(R.id.editText1);
        TextView textView1=(TextView)this.findViewById(R.id.textView1);
        int n=Integer.parseInt(editText1.getText().toString());
        int fact=1;
        for(int i=1;i<n;i++){
            fact=fact*i;
        }
        textView1.setText(""+fact);
    }
}

实验结果:

在这里插入图片描述

程序的初始运行结果和输出12进行阶乘计算的结果:

在这里插入图片描述
程序的初始运行结果和输出10进行阶乘计算的结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值