如何使此程序计入特定数量 [英] How Do I Get This Program To Count To A Specific Number

查看:60
本文介绍了如何使此程序计入特定数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好先在这个网站上发帖。所以我有一个类需要计算到一个特定数字的程序,我把它作为unsigned int bum。我认为问题可能是unsigned int bum可能不是我插入的数字,但我真的不知道。感谢帮助,如果有时间回答和抱歉语法。



GNU nano 2.2.6文件:a8p1.c



hello everyone first post on this site. So i have this program for a class that needs to count to a specific number i have it as unsigned int bum. i think that the problem might be that unsigned int bum might not be the number i insert but i don't really know. thanks for the help if any has the time to answer and sorry for the grammar.

GNU nano 2.2.6 File: a8p1.c

#include <stdio.h>
int main(void)
{
        unsigned int i = 1;
        unsigned int bum;
printf("insert number to count to: ");
scanf("%d",&bum);
        while (i <= bum)
{
        ++i;
        printf("%u\n", i );

                if( i > bum );
                        break;
}
return 0;
}

推荐答案

为什么不使用简单的for循环?



请看下面:



Why don't you use a simple "for" loop?

Please see below:

//unsigned int i = 1;
unsigned int bum;
printf("insert number to count to: ");
scanf("%d", &bum);
//while (i <= bum)
//{
//  //++i;
//  printf("%u\n", i);

//  if (i > bum);
//  break;
//}
for (int i = 1; i <= bum; i++)
{
    printf("%u\n", i);
}

return 0;


我同意@TheRealSteveJudge,但要突出显示你的程序问题......

问题在于
I agree with @TheRealSteveJudge, but to highlight the problem with your program as it stands ...
The problem is in the line
if( i > bum );

最后看到那个分号?如果我>您已指示该程序不执行任何操作bum意味着行 break 总是执行 - 所以你只能得到一个循环。

你的其他问题出在行

See that semi-colon at the end? You have instructed the program to do nothing if i > bum which means that the line break is always executed - so your only ever get a single loop.
Your other problem is in the line

++i;

这会使计数器在稍后使用之前递增,所以你的计数总是从2开始。

最后,

This increments the counter before it used later, so your count will always start at 2.
Finally, that

if( i > bum )
    break;

- 您已经定义了使用保持循环的条件(i< = bum)因此,您的更正代码将是

is not required at all - you have already defined the criteria for staying in the loop with while (i <= bum)So your corrected code would be

#include <stdio.h>
int main(void)
{
        unsigned int i = 1;
        unsigned int bum;
        printf("insert number to count to: ");
        scanf("%d",&bum);
        while (i <= bum)
        {
            printf("%u\n", i++ );
        }
        return 0;
}

但是我现在推荐你解决方案1 ​​

However I now refer you to Solution 1


这篇关于如何使此程序计入特定数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆