2016-03-08 66 views
-2

我是编程新手,希望了解循环有人可以帮助我使用我的代码我想根据用户输入的内容显示一个等于2和20之间的数字的星号。
这里是我的代码,我不知道如何与这个请大家帮忙着手:循环的基本C++

#include "stdio.h" 
#include "iostream" 

main() 
{ 
    int num1, x; 

    printf("Enter a number between 2 and 20: "); 
    scan ("%d", &num1); 
    getchar(); 
    while (num1 > 1) 
    { 
    for (i=1; i<=num1;i++) 
    { 
     printf ("*"); 
    } 
+0

只要摆脱'while(num> 1)'语句。 – fuzzything44

+8

你从哪里学习?请不要亲自接受,但几乎每一行都有错误或不正确的做法。我们确实有[推荐的图书列表](http://stackoverflow.com/q/388242/1171191)。 – BoBTFish

回答

0
#include <iostream> 
using namespace std; 
int main() 
{ 
    int num; 



    cout << "Enter a number between 2 and 20: "; 
    cin >> num; 

    if(num > 1 && num < 21) 
    { 
     for(int i = 0; i < num; i++) 
     { 
      cout << "*" << i << endl; 
     } 
    } 

    return 0; 
} 

我不知道我理解你的问题,所以让我问你这一点。假设用户输入数字12,那么你是否应该输出12个星号?

或者你应该在每个数字前显示一个星号,并使星号的数量与所述数字相对应?

或者你是否在每个数字前打印一个星号,就像我在这里完成的一样?

继续前进,基本for循环声明了一个计数器变量,将该计数器作为对照条件进行检查。你会在我的例子中看到i = 0,并且只要我的< num就执行for循环。 i ++递增计数器。

+0

评论答案时,您应该了解如何编写基本的C++。此代码格式正确,旨在生成特定的输出,您不必喜欢它,但它没有错。 @ BoBTFish在你的代码中使用名字空间是不错的做法,因为你可以包含多个名字空间,当程序员认识到某些事情会与另一个名字空间发生冲突时,你会意识到这一点,而且在这样的简单代码中,你的注释仅用于表明你正在糟糕的一天,并想尝试在互联网上造成麻烦。 – Afflicted

+0

@BobTFish我没有公开这个问题,我提供了一个潜在的答案,通过显示Op并描述了for循环的基本用法,这个人是新的,他/她没有理由不考虑不使用名称空间。你的观点没有实际意义,你的评论被误导了。 – Afflicted

0

让我们保持简洁。 我们有2件事情需要做 -

  • 让用户输入一个数(假设,N)
  • 打印 “*”(不带引号)n次。

    #include<iostream.h> 
    /* 
    
    if compiler is not turboC or is gc++ or any other use #include<iostream> instead 
    also add using namespace std; (just before main and not inside any variable) 
    
    */ 
    
    int main() 
    { 
    
    int n,i; //n is what user will enter & i is for-loop variable 
    
        for(i=1;i<=n;i++) 
        { 
        cout<<"*"; 
    
        /*this line will print the asterick the same no. of times the loop will run 
        which is from 1 to n , that is n times */ 
    
        } 
    
    return 0; 
    
    } 
    

希望,它会清除您的疑惑! 不断提问!保持好奇心! :D

+0

这是'',而不是''。 – GManNickG

+0

请阅读程序内的评论....这将清除你的疑问! –

0

我认为您接受来自用户的整数输入并打印多个星号。

这里是一个非常基本的解决方案:

int main() 
{ 
    int numAsterisk, i; //one stores the number of asterisks, other one used in the loop 
    scanf(" %d", &numAsterisk); 
    for(i = 1; i <= numAsterisk; i++) 
    { 

     printf("* "); 
    } 

    return 0; 
} 

您可以使用,而不是一个“而”循环的“对”,如果你愿意的话,但只记得更新计数器变量,以避免不幸的无限循环。

快乐编码!