-1

I'm learning C, and am currently working my way up through command-line programs. I'm interested in writing a program which would add n terms to eachother, much like would a normal calculator. The number n would be defined by the number of terms the user enters (as opposed to a user-specified n inputted explicitly by the user before the operation). How can this be done? Should I use a while loop for this?

So far, I've tried simply defining a finite number of terms a user can enter (up to 10 terms, if it's fewer, simply replace the remaining terms with zeros).

scanf("%f%c%f%cf%cf%cf%cf%cf%cf%cf%cf", &num1, &op, &num2, &op, &num3, &op, &num4, &op, &num5, &op, &num6, &op, &num7, &op, &num8, &op, &num9, &op, &num10);

    // addition
    if (strcmp(&menuchoice, "a") == 0)
        {
            num3 = num1+num2+num3+num4+num5+num6+num7+num8+num9+num10;
            return num3;
        }
4

1 回答 1

3

如果您只想在输入n 个数字后显示总和,您必须有办法找出所有数字都已输入。一种方法是设置一个用户可以输入的标记值。这可能是一个空行或一个字符串,如=. 如果您只是添加正数,则可以使用负数0表示数字已全部输入。

while (1)
{
    /* get input */
    if (/* should exit */)
        break;
    sum += input;
}
/* show sum */

如果您尝试模拟计算器,您可以在输入每个数字后简单地显示运行总计。这样你就不会知道n有多大。

while (1)
{
    /* get input */
    sum += input;
    /* show sum */
}
于 2013-02-05T02:30:53.503 回答