2

我正在编写一个必须执行分数运算的程序,并且用户必须能够以 w/x(运算符)y/z 的形式输入表达式。(即 1/2 + 1/4。)如何获取该输入并将其不同部分分配给不同的变量,即分子、分母和运算符?

4

3 回答 3

2

使用scanf("%d/%d %c %d/%d", ...). 如果您愿意,可以使用跳过运算符和操作数之间的空格scanf("%d/%d%*[ \t]%c%*[ \t]%d/%d", ...);

于 2012-10-12T18:33:33.967 回答
1

如果您的教授还没有教您 scanf(),您可以使用 cin 获取输入,然后使用教授教您的方法对其进行解析。

阅读本文应该可以帮助您理解。

于 2012-10-12T18:46:45.190 回答
0

Supposing that you can assume that the input is well-formed, you can read a fraction by reading its constituent parts, similar to this:

int numerator, denominator;
char slash;
std::cin >> numerator >> slash >> denominator;

Wrap that in a function that returns an instance of the data structure you're representing fractions with.

Then handle the operators.

于 2012-10-12T19:51:23.877 回答