简体   繁体   English

程序如何在c中运行?

[英]How does a program run in c?

I'm just learning programming with c.我只是在学习用c编程。 I wrote a program in c that had a bug in the body of the while loop I did not put {} .我用 c 编写了一个程序,在我没有放{}的 while 循环体中有一个错误。 The program is as follows, but the question that came to me later is how to run the program in c?程序如下,但后来我的问题是如何在c中运行程序? Why does error 2 not print while it is before the start of the while loop?为什么错误 2 在 while 循环开始之前不打印? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?如果c语言是编译器,为什么不先指定整个程序的错误,到第15行程序执行没有任何问题呢?

int main()
{

    int n ,k;
    float d ;
    printf("please write your arithmetic sequence sentences ");
    scanf("%d",&n);
    printf("\n");
    printf("please write your common differences");
    scanf("%d",&k);
    printf("\n");
    printf("please write your initial element ");
    scanf("%f",&d);
    printf("error 1");
    printf("\n");
    printf("error 2");
    printf("number \t sum");
    printf("erorr 3");
    int i = 0;
    int j = 0;
    int sum = 0;
    while (i < n)
        j = d + i*k;
        sum += j;
        printf("%d\t%d",j,sum);
        i++;

    return 0;
}

Firstly, the program enters an infinite loop:首先,程序进入一个无限循环:

while (i < n)
    j = d + i*k;

Since the values of i and n do not change, the condition never becomes false.由于in的值不变,因此条件永远不会变为假。

Secondly, the printing sequence:二、印刷顺序:

printf("error 2");
printf("number \t sum");
printf("erorr 3");

does not display a line break at the end.最后不显示换行符。 The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens.输出被缓冲(内部存储)等待打印换行符,这自然不会发生。 Add \n at the end of "erorr 3" to see the difference.在“erorr 3”末尾添加\n以查看差异。

#include <stdio.h>
int main()
{
    int n ,k;
    int i = 0;
    int j = 0;
    int sum = 0;
    float d ;

    // If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
    printf("please write your arithmetic sequence sentences ");
    if(scanf("%d",&n)){
        printf("please write your common differences");
        if(scanf("%d",&k)){
            printf("please write your initial element ");
            if(scanf("%f",&d)){
                printf("Number \tSum\n");
            } else {
                printf("error");
            }
        } else{
            printf("error");
        }
    } else{
        printf("error");
    }

    // This is where the values get solved
    // You also forgot to add {} in your while statement
    while (i < n){
        j = d + i*k;
        sum += j;

        printf("%d\t%d",j,sum);
        i++;
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM