C,在控制台上没有输出我的switch语句

时间:2018-11-15 18:46:54

标签: c if-statement switch-statement

我目前正在尝试练习自己在大学学习过的功能,以备即将到来的测试。我正在尝试使用以下功能; ifswitchscanfprintffor

但是,当我尝试在控制台上执行程序时,一旦在变量n中输入了内容,切换功能就不会在控制台上显示任何输出,并且程序结束。

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
    int n,i,x,y,z;
    float res;
    printf("Please input x,y,z using (,)\n");
    scanf("%d,%d,%d",&x,&y,&z);
    printf("You inputed the following numbers: x=%d, y=%d, z=%d\n",x,y,z);
    printf("Which of the following equations would you like to run?\n");
    printf("x+y/z ?? (1)\n");
    printf("sqrt(z)+(x^3/y) ?? (2)\n");
    printf("The average number of the three entered ?? (3)\n");
    printf("Print the word 'test' as many times as is the sum of x,y,z ?? (4)\n");
    scanf(" %d",n);
    switch(n)
    {
    case 1:
        if(z!=0)
        {
            res=(float)(x+y)/z;
            printf("The result is: %f \n",res);
        }
        else
        {
            printf("Division by zero?!\n");
        }
        break;
    case 2:
        if((z>=0)&&(y!=0))
        {
            res=(float)sqrt(z)+((float)pow(x,3)/y);
            printf("The result is: %f \n",res);
        }
        else if(z<0)
        {
            printf("Square root attempted to use negative integer\n");
        }
        else if(y=0)
        {
            printf("You cannot devide with zero\n");
        }
        else
        {
            printf("what?");
        }
        break;
    case 3:
        res=x+y+z/(float)3;
        printf("The average of x+y+z is: %f\n",res);
        break;
    case 4:
        res=x+y+z;
        for(i=1; i<res; ++i)
        {
            printf("test\n");
        }
        break;
    default:
        printf("Please input a number between 1-4!!!\n");
    }
    return 0;
}

2 个答案:

答案 0 :(得分:2)

问题可能出在此语句中
scanf(" %d",n);
更改为
scanf(" %d",&n);
说明:由于缺少地址操作符scanf(" %d",n);

&不允许用户在控制台上输入

答案 1 :(得分:0)

scanf(" %d",n);修改为scanf(" %d",&n);,就像在x,y,z的第一行scanf上所做的一样。
如果要使用#include <math.h>sqrt(),还需要pow()
初始化所有变量也是一种好习惯