编写一个程序

来源:互联网 发布:游戏王ygocore mac 编辑:程序博客网 时间:2024/05/04 11:41

问题描述:

编写一个程序,要求用户输入一串整数和任意数目的空格,

这些整数必须位于同一行中,但允许出现在该行中的任何位

置。当用户按下键盘上的“Enter”建时,数据输入结束。程序

自动对所有的整数进行求和并打印出结果。


c语言版本:(程序来源网上)

#include <stdio.h>
#include <stdlib.h>

void main()
{
      int i;
      int sum = 0;
      char ch;

      printf("Please input a string of integers and arbitrary 

number of spaces: ");

      while( scanf("%d", &i) == 1 )
      {
            sum += i;

            while( (ch=getchar()) == ' ' )
                  ;
            if( ch == '\n' )
            {
                  break;
            }

            ungetc( ch, stdin );
      }

      printf("The result is: %d", sum);
      printf("\n");
      system("pause");
}


c++版本:(程序来源网上)

#include <iostream>

using namespace std;

int main()
{
      int sum = 0;

      cout << "Please input a string of integers and 

arbitrary number of spaces:"<<endl;
      int i;
      while( cin >> i )
      {
            sum += i;
            while( cin.peek() == ' ' )
            {
                  cin.get( );
            }
            if( cin.peek( ) == '\n' )
            {
                  break;
            }
      }
      cout <<"The result is:"<<sum<<endl;
    return 0;
}

0 0
原创粉丝点击