编写计算阶乘的程序

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

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进行阶乘计算的结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45828598/article/details/109061030
今日推荐