Compiles smoothly, does not run, no output (C)

雨燕双飞 提交于 2019-12-24 11:42:13

问题


I was just copying some sample programs taken from the book The C Programming Language by Kernighan and Ritchie. This is one of its examples, a program that claims to convert a C-string inputted to its floating point equivalent:

#include <ctype.h>

/* atof: convert string s to a double */
double atof(char s[])
{
    double val, power;
    int i, sign;

    for (i = 0; isspace(s[i]); i++); /* skip white spaces */
        sign = (s[i] == '-') ? -1 :1; 

    if (s[i] == '+' || s[i] == '-')
        i++;

    for (val = 0.0; isdigit(s[i]); i++)
        val = 10.0 * val + (s[i] - '0');

    if (s[i] == '.')
        i++;

    for (power = 1.0; isdigit(s[i]); i++) {
        val = 10.0 * val + (s[i] - '0');
        power *= 10.0;
    }       
    return sign * val / power;
}

It does compile but I believe it does not run because nothing happens. When I try to "Run" the program, I got this pop-up message:

Where did I go wrong?

Besides I never see the outputs from other sample programs shown in the book.


回答1:


The main function is the entry point for every C progam that should run self-sufficient. You can read something about it here on Wikipedia:

The main() function is special; normally every C and C++ program must define it exactly once.

If you're programming a library (.dll in Windows/.so in Linux) you wouldn't provide a main function as you just provide functions to other programmers. The library is not a running program itself.

In my copy of the book which is the second edition they talking about the main function on page 6.

Provide the following and you will see output you also have to include #include <stdio.h>:

int main()
{
   /* declare variables and initialize some of them */
   char   doubleStr[] = "3.14";
   double doubleVal;

   /* invoke your atof function */
   doubleVal = atof(doubleStr);

   /* print output to console */
   printf("The string \"%s\" is converted to: %f", doubleStr, doubleVal);

   return 0;
}



回答2:


You don't have main() function in your code. That's why you are getting the notification. In C language your program must have a main function to compile and run. The compilation of any program starts from main. Also the example in book generally have only the code of the required function not the main function, They assume that you know basics of c language.

Add following lines to your code, it will work.

int main(void) {
    double a = atof("20");
    printf("%f", a);

    return 0;
}


来源:https://stackoverflow.com/questions/45158875/compiles-smoothly-does-not-run-no-output-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!