n个数之和 [英] Sum of n numbers

查看:147
本文介绍了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()的

从手动


  

格式字符串包含的指令序列的(...)


  
  

一个指令是以下之一:


  
  

的空白字符(空格,制表符,换行符等;见A序列
  isspace为(3))。该指令匹配任意数量的空格,包括
  无,在输入。


另外请注意,标准输入被缓冲,所以结果是从你所期望的有一点不同:

 男人标准输入


  

注释


  
  

流的标准错误的无缓冲。流的标准输出的是行缓冲时,
  它指向一个终端。部分生产线将不会出现,直到fflush(3)或
  出口(3)被调用,或打印一个新行。这可能会产生意外
  结果,尤其是调试输出。的缓冲模式
  标准流(或任何其他流)可以用函数setbuf改变(3)
  或setvbuf用来(3)调用。请注意,在情况下的标准输入与终端相关联,
  也可能有输入缓冲的终端驱动,完全
  无关的标准输入输出缓冲
。 (事实上​​,通常端子输入是线
  缓冲在内核。)这个内核输入处理可以使用改性
  像tcsetattr调用(3);还请参阅stty(1),和termios的(3)。


所以,让我们看一步的程序步骤。

您的程序开始运行,并输入数字2。这是输入缓冲区的样子:

  2 \\ n

scanf函数(%d个,&安培; M)分配2到 M 变量,并开始尝试匹配的空间。它得到一个 NL EOL 。控制仍然是这个 scanf函数,因为它只是匹配一个换行符(被认为是空白),并正在等待匹配更多,而是它得到了结束的行,所以还是等待,当你键入:

  1 \\ n

标准输入再次读取并识别出输入流中的下一个字符不是空间和回报(这是格式字符串条件已完成)。在这一点上,您进入循环和你的下一个 scanf函数(%d个,试验#)被调用,它要读整数的它确实的:它读取1并存储在 NUM 变量。然后重新启动匹配空白字符和获得新线和它重复上面的图案。然后,当你输入:

  2 \\ n

这是第二个 scanf函数获得比空白不同的字符
和回报,让您的循环范围不断执行打印当前
该回路断线条件不满足,所以重新开始。它调用
scanf函数,它有效地读一个整数到变量,那么,
模式重演...

  3 \\ n

它正在等待一个空白,但它有一个字符,而不是。所以,你的
scanf函数收益现在的回路断线条件满足。这是您退出循环,打印出整个和获取的 weired砍伐它
补充说:3个数字,但总和只增加前2
的(如你意
摆在首位)。

您可以检查3挂在标准输入用一个简单的除了你的code:

 的#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价值);
    }    而((C =的getchar())!='\\ n')
        的printf(仍然在缓冲区:%C,C);    返回0;
}

这将输出(与上面的投入,淡然的):

  $ ./sum1
2
1
2
总和值= 1
3
总和值= 3
仍然在缓冲区:3

#include <stdio.h>

int main()
{   
    int m,i,sum,num;

    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);
        //continue;
    }
    printf("Sum= %d ",sum);
}

In the above code it should display the sum of n numbers. But in my code it is taking one extra value of m (m is number of values to take to compute the sum).

For example if I take m as 3 it takes 4 input and displays the sum of 3.

解决方案

As others(@BLUEPIXY and @BillDoomProg) have already pointed in the comments, your problem is the space in your scanf format string. Also check this answer.

Change both your scanf format string from:

scanf("%d ",&m);
...
scanf("%d ",&num);

To:

scanf("%d", &m);
...
scanf("%d", &num);

Just remove the space and it will work fine.

scanf()

From the manual

The format string consists of a sequence of directives(...)

A directive is one of the following:

A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.

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

man stdin

Notes

The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed. This can produce unexpected results, especially with debugging output. The buffering mode of the standard streams (or any other stream) can be changed using the setbuf(3) or setvbuf(3) call. Note that in case stdin is associated with a terminal, there may also be input buffering in the terminal driver, entirely unrelated to stdio buffering. (Indeed, normally terminal input is line buffered in the kernel.) This kernel input handling can be modified using calls like tcsetattr(3); see also stty(1), and termios(3).

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-space and returns, so your loop scope keeps executing printing the current sum. The loop break condition is not met, so it starts again. It calls the scanf and it effectively reads an integer into the variable, then the pattern repeats itself...

3\n

It was waiting for a white-space but it got a character instead. So your scanf 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 intended in 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个数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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