【问题标题】:Creating my own calcutor but program doesnt work创建我自己的计算器,但程序不起作用
【发布时间】:2013-09-05 10:10:05
【问题描述】:

我决定使用代码制作一个计算器,但我的程序无法正常工作。 当我输入我的操作数和新数字时,它似乎不会扫描操作数和数字,也不会启动循环。 感谢您的帮助。

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

float add(float x,float y);
float sub(float x,float y);
float div(float x,float y);
float exp(float x,float y);
float mult(float x,float y);
int main(){

float y,x;
char op;

printf("Type in a number\n");
scanf("%f",&x);
printf("Type in your operand and desired number\n");
scanf("%c",&op);
scanf("%f",&y);


while (!(op=='q')){
    if(op=='+'){
    printf("Your result is %.1f\n",add(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='-'){
    printf("Your result is %.1f\n",sub(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='*'){
    printf("Your result is %.1f\n",mult(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='/'){
    printf("Your result is %.1f\n",div(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='^'){
    printf("Your result is %.1f\n",exp(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }

}

    printf("Your final result is %.1f\n",x);

        return(0);
}

float add(float x,float y){
return (x+y);

}

float sub(float x,float y){
return (x-y);
}

float div(float x,float y){
return (x/y);
}

float exp(float x,float y){
x=pow(x,y);
return(x);
}
float mult(float x,float y){
return (x*y);
}

【问题讨论】:

  • 你的函数 exp 重命名冲突。
  • 是的,我知道我把它改名了,谢谢
  • 这个想法很简单,但您的解决方案并不好,将数字和字符与 scanf 混合读取真的很痛苦,因为 scanf 会留下空白。此外,这些 if 在放入 switch 时看起来更好。当用户没有输入正确的操作数时,你不处理这种情况。
  • 我还是个 c 初学者,所以我在学习,但是这个 while(getchar()!='\n') continue;
  • 让我感到困惑,我应该像在循环中的第一个 scanf 之后还是在两个 scanfs 之后一样输入那个 getchar ......对不起,如果我无法理解它们的放置位置

标签: c function math calculator


【解决方案1】:

当你这样做时

scanf("%c",&op);

您读取了输入缓冲区中的第一个字符。之前的 scanf 将 \n char 留在了其中,因此您读取了该 char。

你想要做的,就是把scanf留下的所有东西都去掉。

while(getchar()!='\n')
  continue;

这将在您尝试读取之前清空缓冲区。

此处每次使用 scanf 都会在缓冲区中留下换行符,因此要摆脱他,每次尝试从输入中读取字符时都使用上述循环,并且您知道换行符就在那里。

【讨论】:

  • 代码要求输入一个数字,读取它,然后它要求输入操作数和第二个数字,这样它就可以正常工作了。
  • 什么都没有?按照预期转到 scanf(%c...)。
  • 在第一次和第二次扫描之间你放了我给你的循环。
  • 当您在 scanf 之后立即从输入中读取字符时,在每个地方。这就是使用 scanf 读取值和字符的代价。您只需要一直专注于缓冲区中的内容。
  • @luserdroog 这可能发生在任何人、任何地点、任何时间:)
【解决方案2】:

我认为发生的事情是换行符(return/enter 键)在scanf("%f",&amp;y); 调用之后留在输入流中,这就是存储为scanf("%c",&amp;op); 调用中的单个字符。

因此,此时您需要丢弃换行符。最简单的方法是在需要读取单个字符时调用scanf("%c",&amp;op);两次。这应该适用于 Mac 和 Unix。对于 Windows,您可能需要读取字符 三次 次,因为 Windows 通常将序列“\r\n”视为换行符序列

为了可移植性,您可以使用这样的循环:

do {
    op = getchar();
} while (op == '\n' || op == '\r');

并删除scanf("%c",&amp;op);。这个循环替换了它。


另一种选择是要求scanf 自己丢弃初始空白。

scanf(" %c",&op);
//     ^ space

另外,请参阅我对this very similar question 的回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2021-02-19
    • 1970-01-01
    • 2015-08-14
    • 2014-01-06
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多