gpt4 book ai didi

c - 如何在 C 中更改月份日期时使代码重复自身?

转载 作者:行者123 更新时间:2023-11-30 20:32:36 25 4
gpt4 key购买 nike

我已经完成了这段代码,并且我做了一个循环,我的代码将从头开始重新启动,但是我希望程序在更改月份日期的同时重新启动,并询问用户他们想要多少个月,以便程序将运行一定次数,因为我添加了 1 月作为第一个月。

#include<stdio.h>
#include<stdlib.h>
float twag(float amount,float rate)
{
float si;
si = (amount * rate) / 100;
return si;
}

float twag2(float amount,float rate)
{
float er;
er = twag(amount, rate) + amount;
return er;
}

int main()
{
char answer;
do {
float amount;
float rate;
float si;
float er;

printf("Month1\n");

printf("\nEnter intial deposit : ");
scanf("%f", &amount);

printf("\nEnter Rate of Interest : ");
scanf("%f", &rate);

printf("\nSimple Interest : %.2f \n", twag(amount,rate));

printf("\nEnd Payment: %.2f \n",twag2(amount,rate));

if (amount <= 100)
printf("interest rate should be 10%%\n");

else if (amount <= 200)
printf("interest rate should be 50%%\n");

else if (amount <= 500)
printf("interest rate should be 80%%\n");

else if (amount >= 500)
printf("interest rate should be 90%%\n");
system("PAUSE");


printf("\nPress Y to continue to the second month or Press any Key To
Exit");
scanf(" %c", &answer); //
}
while (answer == 'y' || answer == 'Y');

return 0;
}

最佳答案

假设您要应用每月利息,您至少需要保留从今天开始的当前月份和年份的记录,因此实现这一点的方法是使用本地时间

void get_date(int *month, int *day, int *year)
{
struct tm *current;
time_t timenow;
time(&timenow);
current = localtime(&timenow);
*month = current->tm_mon+1;
*day = current->tm_mday;
*year = current->tm_year+1900;
}

我建议你 read here 为什么 system("PAUSE") 不好,除此之外,您在循环内定义了循环变量,这意味着它们将在每次循环时重置,以及您的兴趣在循环期间应保持不变,因此您的代码应如下所示

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

float twag(float amount,float rate);
float twag2(float amount,float rate);
void get_date(int *month, int *day, int *year);

int main()
{
char answer;
float amount, rate, si, er;
int day, month, year;

printf("\nEnter intial deposit : ");
scanf("%f", &amount);

printf("\nEnter Rate of Interest : ");
scanf("%f", &rate);

get_date(&month, &day, &year);

do
{
// increment date by 1 month
if (++month > 12) month=1, year++;

printf("\nDate %d/%d/%d \n", day,month,year);
printf("\nSimple Interest : %.2f \n", twag(amount,rate));
printf("\nEnd Payment: %.2f \n",twag2(amount,rate));
amount = twag2(amount,rate);

printf("\nPress Y to continue to the next month or Press any Key To Exit");
scanf("%c", &answer);
}
while (answer == 'y' || answer == 'Y');

return 0;
}

关于c - 如何在 C 中更改月份日期时使代码重复自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47255807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com