使用 Scanf 读入一个随机长度的方程 [英] Using Scanf to read in an equation of random length

查看:42
本文介绍了使用 Scanf 读入一个随机长度的方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读入一个方程,然后分别取每个部分,然后用户可以输入任意大小的方程(例如.3+7、2+-9+8 甚至 2).我有这个但是它似乎不起作用.

I am trying to read in an equation, then take each part separately, however then user can enter as big or small equation as they like (for example. 3+7, 2+-9+8 or even 2). I have this however it doesn't seem to be working.

printf("Please enter an equation\n");

scanf("%f", &num);
//printf("%f", num);


while ( num != '\n'){
scanf("%f", &num);
scanf("%c", &op);
//printf("%c  %f \n", op, num);
}

当我输出我得到的东西时,它与输入不同.

when i output what i have got it is not the same as the input.

推荐答案

您正在尝试使用浮点变量(在您的代码中为 num)中的完整表达式.如果你在 while 循环中执行 scanf("%f", &num); 那么你只是覆盖了 num 中的值.您需要采用 char 数组或 char* 中的表达式.然后你需要有一个算法来分离运算符和数字,将数字转换为所需的类型并解决euation.

You are trying to take the complete expression in a float variable (num, in your code). If you do a scanf("%f", &num); in while loop then you are just overwriting the values in num. You need to take the expression in a char array or char*. Then you need to have an algrithm to seperate the operators and numbers, convert the numbers to desired type and solve the euation.

这篇关于使用 Scanf 读入一个随机长度的方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆