复利计算器 - C.

时间:2015-06-26 03:57:59

标签: c printf scanf

输出完全错误,我预计它会打印一行,然后将我的输入扫描到变量中,然后打印下一行,扫描我的输入等等。但它打印第一行,然后我必须放我的号码两次,它可以做任何事情,而且距离那里只是下坡路。有什么帮助吗?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
    float balance;
    int years;
    float interestRateAnual;
    int frequencyOfInterest;
    double totalCost;

    printf( "Insert amount of money to be deposited.\n" );
    scanf( "%f\n", &balance );

    printf( "How many years for the interest?\n" );
    scanf( "%d\n", &years );

    printf( "What is the anual interest rate?\n" );
    scanf( "%f\n", &interestRateAnual );

    printf( "How many times per year is the interest compounded?\n" );
    scanf( "%d\n", &frequencyOfInterest );

    totalCost = pow(balance*(1 + interestRateAnual/frequencyOfInterest), years);

    printf( "After %d years, with an interest rate of %f% per year, ", years, interestRateAnual );
    printf( "the total you will have to pay is %e.\n", totalCost );


    return 0;
}

2 个答案:

答案 0 :(得分:4)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)  
{   
float balance;   
int years;  
float interestRateAnual;  
int frequencyOfInterest;  
double totalCost; 

printf( "Insert amount of money to be deposited.\n" );
scanf( "%f\n", &balance );

printf( "How many years for the interest?\n" );
scanf( "%d\n", &years );

printf( "What is the anual interest rate?\n" );
scanf( "%f\n", &interestRateAnual );

printf( "How many times per year is the interest compounded?\n" );
scanf( "%d\n", &frequencyOfInterest );

totalCost = balance*pow((1 + interestRateAnual/frequencyOfInterest), (years*frequencyOfInterest));

printf( "After %d years, with an interest rate of %f% per year, ", years, interestRateAnual );
printf( "the total you will have to pay is %e.\n", totalCost );


return 0;
}

答案 1 :(得分:3)

请从所有 \n删除scanf()

  1. scanf( "%d\n", &years );替换为scanf( "%d", &years );
  2. scanf( "%f\n", &balance );替换为scanf( "%f\n", &balance );
  3. 依旧......

    &#39; \ n&#39;第一次调用scanf后,字符仍然留在输入流上,因此第二次调用scanf()会将其读入。

    如果查看scanf的参考文献,您会看到:

      

    格式字符串由空格字符组成(任何单个字符)   格式字符串中的空格字符占用所有可用字符   来自输入的连续空格字符

    所以\ n会触发这种效果,如果你不想要这种行为,就不要理会\ n:

    scanf(&#34;%d&#34;,&amp; years);

    或者,您可以使用以下功能:

    void fflushstdin( void )
    {
        int c;
        while( (c = fgetc( stdin )) != EOF && c != '\n' );
    }
    

    清除输入缓冲区。