如何创建答案之类的输入

时间:2018-10-08 10:20:17

标签: c

我只需要创建输入,以便用户只有两个选项ceilfloor

如果用户选择ceil,则显示void ceil

如果用户选择floor,则显示void floor

#include <stdio.h>
#include <math.h>


void testaval()
{
float ali1, ali2, ali3, ali4;

ali1 = 1.6;
ali2 = 1.2;
ali3 = -2.8;
ali4 = -2.3;

printf("val 1 = %.11f\n", floor(ali1));
printf("val 2 = %.11f\n", floor(ali2));
printf("val 3 = %.11f\n", floor(ali3));
printf("val 4 = %.11f\n", floor(ali4));

}

void testdovom()
{
float ali5, ali6, ali7, ali8;

ali5 = 1.6;
ali6 = 1.2;
ali7 = -2.8;
ali8 = -2.3;

printf("val 1 = %.11f\n", ceil(ali5));
printf("val 2 = %.11f\n", ceil(ali6));
printf("val 3 = %.11f\n", ceil(ali7));
printf("val 4 = %.11f\n", ceil(ali8));

}

int main()
{
char ce[] = {"ceil"};
char fl[] = {"floor"};
printf("hello choose one ceil or floor : 
\n" );
scanf("%s", &ceil);
scanf("%s", &floor);


if ( ce )

testdovom();

else ( fl );


testaval();

return 0;
}

编译在0.33秒内成功完成,但是当我运行它并键入ceilfloor时 程序崩溃。

2 个答案:

答案 0 :(得分:1)

您试图将输入写入函数的地址,这肯定会崩溃。您需要读取这样的字符串:

char buf[256];
scanf("%s", buf);

然后使用strcmp测试字符串是否是您想要的:

if (!strcmp(buf, "ceil")) {
    testdovom();
}
else if (!strcmp(buf, "ceil")) {
    testaval();
}
else {
    printf("Invalid input.\n");
}

答案 1 :(得分:1)

这里需要解决一些基本的编码错误以及逻辑缺陷。

在继续之前,让我们格式化为4个空格

int main()
{
    /* Lets simplify these two statements */
    // char ce[] = {"ceil"};
    // char fl[] = {"floor"};

    char *ce = "ceil";
    char *fl = "floor";

    /* format this into one line .. */
    printf("hello choose one ceil or floor : \n" );
    /* instead of accepting two values, you may want to accept one 
       as per the question asked above the input is either floor or ceil */

    /* lets declare a buffer to store the choice */
    char choice[255];

    /* scan choice */   
    scanf("%s", choice );

    /* Below wont work, ceil and floor are already char * 
       &ceil and &floor will make them char ** so this wont work */ 
    // scanf("%s", &ceil);
    // scanf("%s", &floor);


    /* some commentary on this code snippet below */

    /* 1. ce is an address, a positive integer hence the if statement 
          will always evaluates to true
       2. else has an expression else() that is wrong syntax .
       3. else ending with ; another wrong syntax.

       lets say the below snippet wont compile 

    if ( ce ) 

        testdovom();

    else ( fl );


        testaval();

    */

    /* instead we use strcmp function from string.h 
       and  check if choice is "floor" or "ceil" */

   if( strcmp(choice, ce) == 0 )
   {
        testdovom();
   }
   else if( strcmp(choice, fl) == 0 )
   {
         testaval();
   }
   else
   {
        /* we've got something we donot handle */
        printf("Invalid input");
   }


    return 0;
}