如何让Python复合利息计算器给出正确的答案

时间:2016-01-22 17:30:07

标签: python calculator

之前发过一个关于错误的问题。感谢这里的一些人,我能够解决这个问题。现在,当你输入本金,复利(年度,月度等),利率(0.03等等),以及年数。 其他Q链接:final = P * (((1 + (r/n)) ** (n*t))) TypeError: unsupported operand type(s) for /: 'str' and 'int' 所以从前面的代码我删除了p = 10000,n = 12,r = 0.08,因为当你输入不同的数字时它会给出一个很大的数字。我希望它会用输入的数字来计算它,但它没有。

# User must input principal, Compound rate, annual rate, and years.
P = int(input("Enter starting principle please. "))
n = int(input("Enter Compound intrest rate.(daily, monthly, quarterly, half-year, yearly) "))
r = float(input("Enter annual interest amount. (decimal) "))
t = int(input("Enter the amount of years. "))

final = P * (((1 + (r/n)) ** (n*t)))
#displays the final amount after number of years.
print ("The final amount after", t, "years is", final)
# At the moment it is displaying a very random number.

Enter starting principle please. 1000
Enter Compound intrest rate.(daily, monthly, quarterly, half-year, yearly) 1
Enter annual interest amount. (decimal) 0.01
Enter the amount of years. 1
The final amount after 1 years is 1010.0

最终金额应为1000.10。不确定发生了什么。试图看看是否有办法使P,n,r等于用户输入的数字,这将导致正确的最终答案。

提前致谢。

6 个答案:

答案 0 :(得分:1)

如果您对百分比感兴趣,则应在代码中注意这一点。

final = P * (((1 + (r/(100.0 * n))) ** (n*t)))

答案 1 :(得分:1)

请尝试以下Python代码获取复利:

import React from 'react';
import { ScrollView, View, Text, FlatList, TouchableOpacity, Modal, Alert, StyleSheet, ActivityIndicator, Button, ToastAndroid, TouchableHighlight, UIManager, findNodeHandle } from 'react-native';
import {NEWS_SOURCES, fetch_newsByCountry, fetch_newsBySourceID, fetch_newsFullStory} from '../libraries/loader';


export const Toast=(props)=> {
    if (props.visible) {
        ToastAndroid.showWithGravityAndOffset(props.message, ToastAndroid.LONG, ToastAndroid.BOTTOM, 25, 50);
        return null;
    }
    return null;
};

export default class HeadlinesScreen extends React.Component {
    static navigationOptions= {
        title: 'Headlines',
    };

constructor(props){
          super(props);
          this.state = { channelSource: this.props.navigation.getParam('channel_data', 'none'),   // default value 'none' 
              dataList: [], modalVisible: false, selectedItemId: null, selectedItem_desc: null };
          this._renderItem = this._renderItem.bind(this);
          this._handleItemClick = this._handleItemClick.bind(this);
          this._displayItemDetails = this._displayItemDetails.bind(this); 
          this._setModalVisible = this._setModalVisible.bind(this);   
          this._onFetchComplete  = this._onFetchComplete.bind(this);
          this._forceTriggerSpeak = this._forceTriggerSpeak.bind(this);
      }

      render() {
            console.log('\n\this.props.navigation:', this.props.navigation);
            console.log('\n\nSelected Channel state.params Data: ', this.props.navigation.state.params);
            console.log('\n\nSelected Channel param Data: ', this.props.navigation.getParam('channel_data'));
            console.log('\n\nSelected Channel state Data: ', this.state.channelSource);
            //return (<View></View>) ;
            //console.log('\n\nRender: \n',this.state);
            console.log('\n\nRender -  modal state: \n',this.state.modalVisible);
            return (
                <ScrollView style={styles.container} accessibilityLiveRegion="polite" importantForAccessibility={this.state.modalVisible==false ? 'yes' : 'no-hide-descendants'}>
                    {(this.state.dataList.length ==0? <ActivityIndicator size="large" Accessible={true} accessibilityLabel="Loading news, please wait." /> : 
                        this.state.dataList.map(this._renderItem)
                    )} 
                  <Toast visible={this.state.dataList.length ==0 && this.state.modalVisible==false ? true: false} message="Loading news, please wait." />
                  <Toast visible={this.state.dataList.length > 0 && this.state.modalVisible==false ? true: false} message={this.state.dataList.length+' news loaded. Tap to read headline. And double tap to read details.'} />
                  <Toast visible={this.state.dataList.length > 0 && this.state.modalVisible==true ? true: false} message={'Loading full story, please wait.'} />
                  <Toast visible={this.state.dataList.length > 0 && this.state.modalVisible==true && this.state.selectedItem_desc != null? true: false} message={'Story loaded, please tap on screen to read. And scroll bottom of screen and hit Close button, to close this story.'} />

                  {(this.state.modalVisible ? this._displayItemDetails() : null)}

                </ScrollView>
              );
    }


    async componentDidMount(){
        console.log("\n\n\n", this.props.navigation.getParam('channel_data'));
        var newsList = await fetch_newsBySourceID(this.state.channelSource, this._onFetchComplete);       // external api call
    }

   _onFetchComplete(payload, payloadType){   // payloadType: list | story
        console.log('\n\n onFetchComplete list: \n', payload); 

        if(Array.isArray(payload) && payloadType == 'list'){
            console.log('\n\n onFetchComplete list: \n'+payload.length); 
            this.setState(previousState => {
                return { dataList: payload};
            });
        }
        else{
            this.setState(previousState => {
                return { selectedItem_desc: payload};
            });
        } 
    }


    _renderItem(obj, index){
        return (
            <View key={index} style={{ borderBottomWidth: 1, borderBottomColor: '#ccc', borderStyle: 'solid', padding:10}} >
                <TouchableOpacity style={{flexDirection: 'row', }} onPress={()=>this._handleItemClick(index)} accessible={true} accessibilityLiveRegion="polite" accessibilityLabel={(index-1+2)+". "+obj.title} accessibilityHint="Double tap to read full news on next screen.">
                   <Text style={[styles.lightTxt, styles.rowTxt]} >{obj.title}</Text>
                </TouchableOpacity>
            </View>
        );
    }


    async _handleItemClick(itemIndex){
        console.log('showModal for item: '+itemIndex);
        fetch_newsFullStory(this.state.dataList[itemIndex].story_url, this.state.channelSource, this._onFetchComplete);
    }

    _forceTriggerSpeak(){
        UIManager.sendAccessibilityEvent( findNodeHandle(this), UIManager.AccessibilityEventTypes.typeViewClicked);  
    }

            // usually item details in a Popup Modal View
    _displayItemDetails(){  // this.state.dataList[this.state.selectedItemId].content
        console.log('\n\nDisplay Modal:\n', this.state.modalVisible);
    }

          // usually used to hide Popup Modal
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 15,
        backgroundColor: '#000',
    },
    lightTxt: {
        color: '#fff'
    },
    rowTxt:{
        padding:25
    },
});

答案 2 :(得分:0)

基于此: 复利公式 FV = P(1 + r / n)^ Yn, 其中P是初始本金,r是年利率,Y是投资年数,n是每年的复利期数。 FV是终值,表示本金在Y年后增长到的金额。

P = int(input("Enter starting principle please. "))
n = int(input("Enter number of compounding periods per year. "))
r = float(input("Enter annual interest rate. e.g. 15 for 15% "))
y = int(input("Enter the amount of years. "))

FV = P * (((1 + ((r/100.0)/n)) ** (n*y)))

print ("The final amount after", y, "years is", FV)

答案 3 :(得分:0)

P = int(input("Enter starting principle please: "))
n = int(input("Enter number of compounding periods per year: "))
r = float(input("Enter annual interest rate: "))
y = int(input("Enter the amount of years: "))

FV = P * (((1 + ((r/100.0)/n)) ** (n*y)))

print ("The final amount after", y, "years is", FV)

答案 4 :(得分:0)

# name
NAME=raw_input("Enter Name= ")

# Principle amount
P =float(input("Enter Principle Amount: "))

# Rate of interest
R = float(input("Enter rate of Interest: "))

#No Of years
T = float(input("Enter No of Years= "))

#compound interest calculation
CI = P * ( 1 +  R / 100)**T

print"compound interest is {:.2f}".format(CI)

答案 5 :(得分:0)

每年计算复利的公式是

A = P(1 + R / 100)t

复利= A – P

在哪里, A是金额, P是本金, R是比率, T是时间跨度

def compound_interest(principal, rate, time):
    Amount = principal * (pow((1 + rate / 100), time)) 
    CI = Amount - principal
    print("Compound interest is", CI) 
compound_interest(100000000, 14, 8)