【问题标题】:How to increment months loop. Then display from then如何增加月份循环。然后从那时开始显示
【发布时间】:2017-02-14 17:08:29
【问题描述】:

大家见鬼!我是编程的菜鸟。我试图搜索类似于我正在寻找的东西,但我不能完全理解类似的例子。

我想做的是让用户输入几年,将年转换为月。然后在使用月份变量时在列表中显示从第 1 个月到全部月份。我需要循环继续,直到它达到完整的几个月,然后停在那里。以下是我目前所知道的以及我所学到的。我怀疑我可能需要使用某种类型的计数器变量,但不知道该怎么做。

int main(){
int years, months;
printf("Enter years ");
scanf_s("%d", &years);

months = years * 12;
printf("Months is %d ", months); 

do {
    printf("Month", ); //Month 1,2,3,4........24 up to full amount that was converted from years//
} while ();
return 0;

【问题讨论】:

  • 使用辅助变量来维护您已经显示的月数。在循环中通过递减它的值来迭代直到月数达到 0。
  • 做 { printf("%d, ", counter);月——;而(月!= 0);
  • 谢谢!我之前尝试过递减,但不知道如何按顺序转。
  • 在下面添加了一个带有链接的答案,以便您了解循环的工作原理。

标签: c++ loops counter


【解决方案1】:
int count = 1;
while (month != 0) {
   printf("%d, ", count);
   month = month - 1;
   count = count + 1;
} 

【讨论】:

  • 谢谢!我终于得到了正确的结果!我将彻底检查这一点,以便将来使用这种经验。
【解决方案2】:

看看循环、while、for 和 do-while。这是一个简单直接的教程的链接:https://www.tutorialspoint.com/cprogramming/c_loops.htm

对于您的问题,只需创建一个用 1 初始化的额外变量并循环,直到它通过月份的值。

int years = 0;
int months = 0;
int counter = 1;

printf("Enter years ");
scanf("%d", &years);

months = years * 12;
printf("Months is %d ", months);

printf("Months: ");

do {
    printf("%d ", counter); //Month 1,2,3,4........24 up to full amount that was converted from years//
    counter++;
} while (counter <= months);

return 0;

【讨论】:

  • 非常感谢!我不知道我可以初始化年、月等。这就是我遇到麻烦的主要原因。我复制了您的代码并对其进行了调整以使用其他变量来实现它。
  • 总是初始化你的变量!甚至指针 - 带有 NULL。希望您在社区中学到很多东西。祝你有美好的一天。
  • 是的,我无法编辑,但我想说的是使用 = 0 进行初始化。当然期待学习和贡献。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多