本文介绍了n个数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的#include<&stdio.h中GT;诠释的main()
{
    INT M,I,和,NUM;    I = 0;
    总和= 0;
    scanf函数(%d个,&安培; M);
    而(ⅰ&所述M){
        scanf函数(%D,试验#);        总和=总和+ NUM;        I = I + 1;
        的printf(,合计金额=%d个\\ n价值);
        //继续;
    }
    的printf(总和=%d个,总和);
}

在上面的code应该显示n数字的总和。但在我的code它走m个额外的价值(m是值的数量取来计算的总和)。

例如,如果我,采取并购为3它需要4个输入和显示3的总和。


解决方案

正如其他(@BLUEPIXY和@BillDoomProg)已在评论中指出,你的问题是在你的 scanf函数格式字符串。还要检查。

同时改变你的 scanf函数格式字符串来自:

  scanf函数(%d个,&安培; M);
...
scanf函数(%D,试验#);

要:

  scanf函数(%d个,&安培; M);
...
scanf函数(%D,试验#);

只是删除​​了空间,而且将正常工作。

scanf()的

从手动

Also note that stdin is buffered, so the results are a little different from what you would expect:

man stdin

So, lets examine your program step by step.

Your program starts running and you enter the number 2. This is what the input buffer looks like:

2\n

scanf("%d ", &m) assigns 2 to the m variable and starts trying to match a space. It gets a NL and EOL. Control is still with this scanf because it just matched a newline (considered a white-space) and is waiting to match more, but instead it got the End-Of-Line, so it is still waiting when you type:

1\n

Then reads stdin again and realizes that the next character in the input stream is not a space and returns (it's format string condition was done). At this point, you enter the loop and your next scanf("%d ",&num) is called and it wants to read an integer, which it does: it reads 1 and stores that in the num variable. Then again it starts matching white-spaces and gets the new-line and it repeats the above pattern. Then when you enter:

2\n

That second scanf gets a character different than a white-spaceand returns, so your loop scope keeps executing printing the current sum.The loop break condition is not met, so it starts again. It calls thescanf and it effectively reads an integer into the variable, then thepattern repeats itself...

3\n

It was waiting for a white-space but it got a character instead. So yourscanf returns and now the loop break condition is met. This is where you exit your loop, prints the whole sum and get that weired felling that it"added" 3 numbers but the sum is adding only the first 2 (as you intendedin the first place).

You can check that 3 hanging in stdin with a simple addition to your code:

#include <stdio.h>

int main()
{

    int m, i, sum, num;
    char c;

    i = 0;
    sum = 0;
    scanf("%d ", &m);

    while (i < m) {
        scanf("%d ", &num);

        sum = sum + num;

        i = i + 1;
        printf("Value of sum= %d\n", sum);
    }

    while((c = getchar()) != '\n')
        printf("Still in buffer: %c", c);

    return 0;
}

That will output (with the above input, of couse):

$ ./sum1
2
1
2
Value of sum= 1
3
Value of sum= 3
Still in buffer: 3

这篇关于n个数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:44