gpt4 book ai didi

c++ - 在c++中找到用户输入的3个最大数字的平均值

转载 作者:行者123 更新时间:2023-11-28 06:42:04 24 4
gpt4 key购买 nike

所以设计问题是:

输入3个数字,显示最大的。继续输入 3 个数字组,直到用户想要退出。求出所有最大数字的平均值。

所以输入数字工作正常,但是当我尝试插入 SENTINEL 值以停止循环时,我需要为所有 3 个数字输入它,但它没有给我一个正确的平均值对于过去输入的数字。

非常感谢您抽出宝贵时间提供任何帮助!

 #include <iostream>
using namespace std;

int main()
{

const int SENTINEL = -1;
int num1;
int num2 = 0;
int num3 = 0;
int largest;
int sum;
int count;
float average;

// initialize the count and sum
count = 0;
sum = 0;

while (num1 != SENTINEL)
{

// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number ";
cin >> num1;

// Prompt the user for the second number
cout << "please enter second number ";
cin >> num2;

// Prompt the user for a third number
cout << "please enter the third number ";
cin >> num3;

// Compare numbers 1 and 2 for the largest number
if (num1 > num2)
{
largest = num1;
}
else
{
largest = num2;
}

// Compare largest to last number input
if (num3 > largest)
{
largest = num3;
}

// Display the largest number
cout << "largest number is: " << largest << endl;

// Increment the count
count++;

}



if (count > 0)
{
average = sum / count;
cout << "Average of the numbers is " << average;
}

return 0;
}

最佳答案

使用 break; 指令是一种可能,但通常被认为不够优雅且难以维护。

原因是你打破了代码流,你的程序的读者(在大程序中可能不是你,或者如果你分享它)希望你的循环代码继续到它的结尾.如果您的函数有一个或多个 break; 指令,则可能很难理解该函数的意图,因为您必须记住在哪些情况下循环已经结束。

解决问题的基本原则是在正确的位置开始循环,就在获得 num1 的值之后。然后你的循环也必须以它结束。这样,您将始终在用户键入 num1 后立即检查退出条件。

// initialize the count and sum
count = 0;
sum = 0;

// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number ";
cin >> num1;

while (num1 != SENTINEL)
{

// Prompt the user for the second number
cout << "please enter second number ";
cin >> num2;

// Prompt the user for a third number
cout << "please enter the third number ";
cin >> num3;

// Compare numbers 1 and 2 for the largest number
if (num1 > num2)
{
largest = num1;
}
else
{
largest = num2;
}

// Compare largest to last number input
if (num3 > largest)
{
largest = num3;
}

// Display the largest number
cout << "largest number is: " << largest << endl;

// Increment the count
count++;

// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number ";
cin >> num1;
}

if (count > 0)
{
average = sum / count;
cout << "Average of the numbers is " << average;
}

return 0;

注意:我这里没有解决代码错误,如评论中提到的(变量未声明,总和未更新等)。

关于c++ - 在c++中找到用户输入的3个最大数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815186/

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