如何在C中为Ubuntu控制台程序编写条件循环

时间:2012-05-05 15:17:58

标签: c linux

在ubuntu终端中如何在C中编写条件if循环是否可行?这是我必须在大学写的项目。

我认为语言来自于我被告知的语言。

我会用伪代码写出我的问题,任何帮助都会很棒。

global x variable
global y variable

please enter X (x has to be a value between 1-100)
if anything other than 1-100 then repeat and ask for x again

once the value has been identified as 1-100
please enter Y
if anything other than 1-100 enter ask again

once the two values have been entered scan into a 2d array.

示例:

please enter x: d
please enter x: d
please enter x: 5
please enter y: f
please enter y: 5

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 
1 2 3 4 5

感谢您的任何建议。

我的讲师再次说过,这个模块是C和Ubuntu Linux中的控制台,只是为了澄清。

这是我到目前为止所拥有的;对不起它中的所有评论我必须发表评论,以显示他们在任务中所做的一切。

#include <stdio.h>  //this defines the library to use within c//  
#include <stdlib.h> //this defines the library to use within c//
#include <time.h>   //this defines the library to use within c//

int x; /*this sets the initial variables to program*/
int y; /*this sets the initial variables to program*/

int main(void){

printf("Please Enter Size X Of Array:");/*This is where the x limit of the array is set*/
scanf("%d",&x);

我希望它在这里检查输入的值是否在1-100之间,如果它不打印再次输入数组的大小X(Y相同)

printf("\n");

printf("please Enter Size Y Of Array:");/*This is where the y limit of the array is set*/
scanf("%d",&y);

    int array[x][y];/*this sets the initial variables to program*/

任何人都可以发布你如何做到这一点,因为当我尝试时它不起作用。感谢。

2 个答案:

答案 0 :(得分:1)

do {
    printf("Please Enter Size X Of Array:");/*This is where the x limit of the array is set*/
    scanf("%d",&x);
} while (x<1 || x>100);

答案 1 :(得分:0)

我会像这样编写循环:

 for (;;) {
     printf ("Please Enter Size X Of Array: ");
     fflush (stdout);
     if (scanf ("%d", &x) == 1 && x >= 1 && x <= 100) {
         break;
     }
     /* Read a character to prevent looping forever for non-numbers or EOF. */
     if (( x = getchar()) == EOF) {
        exit (EXIT_FAILURE);
     }
 }