gpt4 book ai didi

c++ - 如何从 while 循环中添加数字?

转载 作者:行者123 更新时间:2023-11-28 04:46:58 25 4
gpt4 key购买 nike

代码输出单独的行,但我希望它把所有行加在一起。

示例测试数据文件:

Iris Pruysen 在 2014 年田径残奥会上的表现

艾里斯·普鲁伊森 (Iris Pruysen) 是一名装有假腿的运动员,他在法国巴黎塞巴斯蒂安·查理蒂体育场举行的 2014 年残奥会田径比赛中参加跳远比赛。今天是 2017 年 7 月 27 日。

输出是:

Average number of letters per sentence 163.000  
Total number of digits is 8
Average number of letters per sentence 5.000
Total number of digits is 6

我怎样才能只用一行表示平均字母数和一行表示总数字?

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
using namespace std;
int main()
{
int letters; //Total number of letters
int digits; //Total number of digits
double sentencecount; //Number of sentences
float averageletters; //Average number of letters per sentence
int linecount=0; //Count of lines
char current; //Current character
cout << fixed << setprecision(3);
cin.get(current);
while (cin) //while receiving input
{
digits = 0;
letters = 0;
linecount++;
while (current != '.' && current != '!' && current != '?') //checks each line
{
if (isalpha(current))//counts alphabet characters
letters++;
if (isdigit(current))//counts digits
digits++;
cin.get (current);
}
sentencecount = letters/linecount;//finds average letters per sentence
cin.get (current);
cout << "Average number of letters per sentence " << sentencecount << endl << "Total number of digits is " << digits << endl;
}
// cout << "Average number of letters per sentence " << sentencecount << endl << "Total number of digits is " << digits << endl;
return 0;
}

最佳答案

这是我清理代码的成果。这真的是在正确的时间做正确的事情。您需要考虑什么应该在循环内,什么应该在循环外。例如,很明显,如果您尝试计算字母总数,将字母数设置为零是错误的在循环内

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
using namespace std;
int main()
{
int letters = 0; // Total number of letters
int digits = 0; // Total number of digits
double sentencecount; // Number of sentences
float averageletters; // Average number of letters per sentence
int linecount=0; // Count of lines
char current; // Current character
cout << fixed << setprecision(3);
cin.get(current);
while (cin) // While receiving input
{
linecount++;
while (current != '.' && current != '!' && current != '?') // Checks each line
{
if (isalpha(current)) // Counts alphabet characters
letters++;
if (isdigit(current)) // Counts digits
digits++;
cin.get (current);
}

cin.get (current);
}
sentencecount = letters/linecount; // Finds average letters per sentence
cout << "Average number of letters per sentence " << sentencecount << endl
<< "Total number of digits is " << digits << endl;
return 0;
}

免责声明,我实际上没有测试过上面的代码。

关于c++ - 如何从 while 循环中添加数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com