我想制作一个程序,要求您提供一个六位数字。在屏幕上,我将打印给出的六个单位数字,这些数字的平均值,以及最小值和最大值。
我想到的最简单的方法是创建一个整数表。但是,给出6位数字会使表格在每个数字处使用空格。有一种简单的方法,我可以写一个没有空格的6位数字,并做同样的事情吗?
以下是代码:
#include <iostream>
#include <stdio.h>
#include <cstdio>
using namespace std;
int main()
{
float numb[6], max, min;
int i;
float sum;
float average;
cout << "Give a six digit number: ";
for (i = 0; i < 6; i++) {
cin >> numb[i];
}
cout << "The number you gave its :\n ";
for (i = 0; i < 6; i++) {
printf("%f ,", numb[i]);
}
for (i = 0; i < 6; i++) {
sum = sum + numb[i];
}
average = sum / 6;
cout << "Average is \n" << average;
max = numb[0];
for (i = 0; i < 6; i++) {
if (max < numb[i])
max = numb[i];
}
printf("Largest element: %f", max);
min = numb[0];
for (i = 0; i < 6; i++) {
if (min > numb[i])
min = numb[i];
}
printf("Smallest element: %f", min);
}
答案 0 :(得分:2)
float sum;
sum
在你的程序中未初始化,但之后也使用了 -
for(i=0;i<6;i++){
sum=sum+numb[i];
初始化然后使用它。
答案 1 :(得分:2)
有没有一种简单的方法,我只能写一个没有空格的6位数字并做同样的事情?
做一些事情
std::string input;
std::cout << "Enter a six digits number: ";
std::cin >> input;
if(input.size() == 6) {
for(char C : input) {
// for(size_t I = 0; I < 6; ++I) // C++98 version
// char C = input[I]; // C++98 version
if(std::isdigit(C)) {
int digit = C - '0'; // convert char to a number
// do whatever you want with the digit
}
else {
std::cout << "Error in input, " << C << " is not a digit" << std::endl;
break;
}
}
}
else {
std::cout << "Error: Enter exactly six digits please" << std::endl;
}
您应该注意有关代码示例的一些要点:
float
不应该用于表示数字,它们只是0到9范围内的整数。使用unsigned int
左右(unsigned char
就足够了,但我不想添加混乱)。float
值来获得平均值,则需要将参与计算的整数值转换为float
答案 2 :(得分:1)
sum
时未初始化。numb[0]
)与自身进行比较。 printf
和cout
编辑:忽略我的列表中的第6点(使用6个数字)
#include <iostream>
using namespace std;
int main()
{
cout << "Give a six digit number: ";
//Read numbers
float numb[6];
for (int i = 0; i < 6; i++) {
cin >> numb[i];
}
//Print numbers
cout << "The number you gave its : ";
for (int i = 0; i < 6; i++) {
cout << numb[i] << ",";
}
cout << endl;
//Calculate sum
float sum = 0;
for (int i = 0; i < 6; i++) {
sum = sum + numb[i];
}
cout << "Sum is " << sum << endl;
//Calculate average
float average = sum / 6;
cout << "Average is " << average << endl;
//Calculate max
float max = numb[0];
for (int i = 1; i < 6; i++) {
if (max < numb[i])
max = numb[i];
}
cout << "Maximum is " << max << endl;
//Calculate min
float min = numb[0];
for (int i = 1; i < 6; i++) {
if (min > numb[i])
min = numb[i];
}
cout << "Minimum is " << max << endl;
}