C语言存款利率计算器问题


#include<stdio.h>
#include<math.h>
int main()
{double rate, capital, deposit;
    int year;
    char c = 'N';
    printf("Input rate,year,capital:");
    scanf("%lf %d %lf",&rate,&year,&capital);
    printf("Compound interest(Y/N)? ");
    rewind(stdin);
    scanf("%c",&c);
    if(c=='Y'||c=='y') {
        deposit=capital*pow(1+rate,year);
    }
    else if(c=='N'||c=='n') {
        deposit=capital*(1+rate*year);
    }
    printf("deposit=%.4f\n",deposit);
    system("pause");
return 0;
}

为什么输出结果是这样呢

img

img

  • 后来发现数据输出时如果用空格隔开就不会出现这样的错误

  • 为什么这里用逗号隔开会出错呢

从代码实现上看,使用了条件语句if和else if来判断用户选择的计算方式,并采用数学库函数pow()计算幂次方。
需要注意的是,代码中使用了rewind(stdin)函数清除输入缓冲区。但是,该函数不是标准C语言库函数,有可能在某些编译器上无法通过编译。建议使用fflush(stdin)替换该函数,保证代码的可移植性。
此外,最后一行代码使用了system("pause")语句,在Windows系统上执行该语句会暂停程序的运行,并提示用户“按任意键继续...”,以免程序执行过快导致窗口关闭。但是,在其他操作系统上可能无法正常运行,因此此行代码应该根据具体情况进行修改。