By the task I need to calculate the percent of foreign excellent students (so the country of origin isn't "Ukraine" and the mean mark is greater than 3). But it wouldn't work and I don't know if I input text in the struct variable correctly and than compare it. Please explain this.
The code:
#include <iostream>
#include <ctime>
#include <Windows.h>
#include <cmath>
#include <iomanip>
using namespace std;
struct Student {
char country[15];
int course;
float meanMark;
};
int main() {
Student s[4];
//strcpy_s(s.country, "hjkhj");
//s.country = "ffff";
for (int i = 0; i < 4; i++) {
cout << "Student" << i + 1 << ": " << "\n";
std::cin >> s[i].country;
cin >> s[i].course;
cin >> s[i].meanMark;
}
char u[8] = "Ukraine";
int k = 0;
for (int i = 0; i < 4; i++) {
if (s[i].country != u && s[i].meanMark > 3) {
k++;
}
}
float percent = k / 4 * 100;
cout << "percent = " << percent << "%" << endl;
}
Here is the input:
First goes the country of origin, than course, than mean mark
https://i.stack.imgur.com/kzdKz.png
Here is the output:
The result should be 25%
https://i.stack.imgur.com/7lhNd.png
I think that what u need is to modify the line where you calculate the percentage to
float percent = k / 4.0 * 100.0;
Okay so i changed char to string and it didn't work again, but then i changed places with / 4 and * 100 so the equation looks like float percent = k * 100 / 4;.... and it worked...
Related
I am new to C++, but this picture here is the goal of my program.
This is what I need my input/output to look like:
--- INPUT ---
The first line of standard input contains an integer 1 ≤ C ≤ 50, the number of test cases.
C data sets follow. Each data set begins with an integer, N, the number of people in the class (1 ≤ N ≤ 1000).
N integers follow, separated by spaces or newlines, each giving the final grade (an integer between 0 and 100) of a student in the class.
--- OUTPUT ---
For each case you are to output a line giving the percentage of students whose grade is above average, rounded to exactly 3 decimal places.
This is the code that I currently have:
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using std::vector;
void aboveAverage(int testCases) {
// initialize number of students for vector size
int numOfStudents;
// initialize a vector to hold grades
vector<int> grades;
// for # of testCases, recieve # of students per test case
for(int i = 0; i < testCases; i++) {
std::cout << "Num of Students: ";
std::cin >> numOfStudents;
// per test case, recieve grade per student and push into vector
for(int j = 0; j < numOfStudents; j++) {
int grade1;
std::string grade;
// debug statement
std::cout << "Enter grades: ";
std::getline(std::cin, grade);
grade = int(grade1);
grades.push_back(grade1);
}
}
// sum the vector array and intitialize above average threshold
int sum = std::accumulate(grades.begin(), grades.end(), 0);
// debug statement
std::cout << "Sum = " << sum << std::endl;
int threshold = sum / numOfStudents;
// initialize a counter and based on threshold get the # of elements that
// meet that criteria
int counter = 0;
for(int j = 0; j < numOfStudents; j++) {
// if the grade is larger than the threshold, add to counter
if(grades[j] > threshold) {
counter += 1;
}
}
// get the percentage of those above average and print it out
float percentage = (counter / numOfStudents) * 10;
std::cout << std::setprecision(3) << std::fixed << percentage << std::endl;
}
int main() {
int testCases;
// debug statement
std::cout << "# of Test Cases: ";
std::cin >> testCases;
aboveAverage(testCases);
return 0;
}
The code as a whole runs "fine", I guess you could say. Just no errors in the compiler that yell at me at least. I just cannot, for the life of me, figure out how to set it up exactly like it should for the input. I think I complicated my life with the vector, although it seems easier to me this way. I think I'm close. Hopefully I am!
How can I get specified number?
For example, the number that a user enters is 4568962358.
I want to save the "96" in a variable; how do I get just the 96 or 23?
This is the real problem:
An important shipping company is making the annual inventory of the goods they have in their warehouse, for which they have implemented a system of codes that are assigned to each good that is in said warehouse. This code, which consists of 16 digits, contains the following information: unique number, indicator of whether it is fragile or not, place of origin of the property and expiration date of the property.
The assigned code structure is UUUFPPPPDDMMAAAA where:
UUU: unique number of the good.
F: digit that indicates if the good is fragile or not. If it is 0 it means that it is fragile.
PPPP: ASCII codes of the two letters that identify the country of origin of the good.
DD: Good's due date.
MM: Month of the expiration of the good.
AAAA: Year of expiration of the good.
You are asked to create a C ++ program that receives the assigned code as data and then prints the following data as shown in the example.
Enter the code: 1120677212042015
Then the program must print: Unique number: 112.
Fragile(N: No; S: Yes): S .
Country of origin: CH .
Day, month and year of expiration: 04-12-2015 .
Well it is outdated to date (N : No; S: Yes): S.
In the solution of the problem you will not be able to make use of selective structures.
Version 1
#include "stdafx.h"
#include "conio.h"
#include "iostream"
using namespace System;
using namespace std;
int main()
{
int code;
int UUU;
int F;
int PP1,PP2;
int DD;
int MM;
int AAAA;
cout << "Enter the code: "; cin >> code; // 1120677212042015
// ...code needed here
UUU = int(code / 10000000000000);
cout << "\nRESULTS" << endl;
cout << "\nUnique number: " << UUU << endl; // prints 112
_getch();
return 0;
}
Version 2
I'm not able to do the next parts; please help!
#include "stdafx.h"
#include "conio.h"
#include "iostream"
using namespace System;
using namespace std;
int main()
{
double code;
double UUU;
double F;
double PP1,PP2;
double DD;
double MM;
double AAAA;
cout << "Enter the code: "; cin >> code; // 1120677212042015
UUU = int(code / 10000000000000);
PP1 = int(code / 10000000000) % 100;
PP2 = int(code / 100000000) % 100;
DD = int(code / 1000000) % 100;
cout << "\nRESULTS" << endl;
cout << "\nUnique number: " << UUU << endl; // 112
cout << "Country of origin: " << (char)PP1 << (char)PP2<<endl; //CH
cout << "Day, Month and Year of expiration: " << DD; // 12/../....
_getch();
return 0;
}
One way is using substr concept.
For example, if user enters input as 1120677212042015, then read it into a string and divide the string into sub-strings according to the format UUUFPPPPDDMMAAAA .
std::string sUserCode = "1120677212042015";
std::string sUniqueNumber = str.substr (0,3);
int iUniqueNumber = stoi(sUniqueNumber);
This is one of those occasions where the C library comes in handy :
int UUU, F, PP1, PP2, DD, MM, AAAA;
cout << "Enter the code: "; // 1120677212042015
scanf("%3d %1d %2d %2d %2d %2d %4d", &UUU, &F, &PP1, &PP2, &DD, &MM, &AAAA);
This captures all the values. The spaces in the format string are not necessary, but makes it easier to read.
u can use % and / to do this
4568962358 / 10000 = 456896 %100 = 96
or you can put it in a array and show the part of integer that u want.
int n = 4568962358;
int a[10];
for (int i = 0; i<10 ; i++)
{
a[i] = n%10;
n /= 10;
}
search your question in stack over flow.
these questions have good answers.
Is there any way to get the length of int variable e.g In string we get the length by simply writing int size = string.length();
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i = 0;
cout<<"Please Enter the value of i"<<endl;
cin>>i;
//if user enter 123
//then size be 3 .
// Is it possible to find that size
}
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
int main () {
assert(int(log10(9)) + 1 == 1);
assert(int(log10(99)) + 1 == 2);
assert(int(log10(123)) + 1 == 3);
assert(int(log10(999)) + 1 == 3);
return 0;}
You have a few options here:
(This answer assumes you mean number of printable characters in the integer input)
Read the input as a string and get its length before converting to an int. Note that this code avoids error handling for brevity.
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
cout << "Please enter the value of i" << endl;
string stringIn = "";
cin >> stringIn;
cout << "stringIn = " << stringIn << endl;
size_t length = stringIn.length();
cout << "input length = " << length << endl;
int intIn;
istringstream(stringIn) >> intIn;
cout << "integer = " << intIn << endl;
}
Read in an integer and count the digits directly:
Many other answer do this using log. I'll give one that will properly count the minus sign as a character.
int length_of_int(int number) {
int length = 0;
if (number < 0) {
number = (-1) * number;
++length;
}
while (number) {
number /= 10;
length++;
}
return length;
}
Derived from granmirupa's answer.
Not sure whether it fits your requirement but you could use std::to_string to convert your numeric data to string and then return its length.
For length i assume you mean the number of digits in a number:
#include <math.h>
.....
int num_of_digits(int number)
{
int digits;
if(number < 0)
number = (-1)*number;
digits = ((int)log10 (number)) + 1;
return digits;
}
Or:
int num_of_digits(int number)
{
int digits = 0;
if (number < 0) number = (-1) * number;
while (number) {
number /= 10;
digits++;
}
return digits;
}
Onother option could be this (can works with float too, but the result is not guaranteed):
#include <iostream>
#include <sstream>
#include <iomanip>
...........
int num_of_digits3(float number){
stringstream ss;
ss << setprecision (20) << number;
return ss.str().length();
}
Below is the prompt that I have:
Write a while loop that prints 1 to userNum, using the variable i.
Follow each number (even the last one) by a space. Assume userNum is positive.
Ex: userNum = 4 prints:
1 2 3 4
I've tried a few things and below is the code that I have so far:
#include <iostream>
using namespace std;
int main() {
int userNum = 0;
int i = 0;
userNum = 4; // Assume positive
cout<<("userNum = %d\n",userNum);
while(i != userNum) {
i++;
cout<<("%d",i);
}
cout << endl;
return 0;
}
The output is close to whats needed but its not correct and I cant seem to figure out what I did wrong.
the output is 41234
Could someone please guide me in the right direction as to what I did incorrectly?
The basic mechanism for this is something like this:
#include <iostream>
int main() {
int i = 0;
int userNum = 0;
userNum = 4;
while(i < userNum) {
++i;
std::cout<<i<<" ";
}
}
Output:
1 2 3 4
You could initialize userNum to be from cin if you'd like, naturally.
The problem is because of this line: cout<<("userNum = %d\n",userNum).
cout does not support a formatting like that. And this resulted in a weird behaviour: it skipped the userNum = part and just printed userNum as int value, which is the first number 4 in your output.
Try to consider the following code instead:
#include <iostream>
using namespace std;
int main() {
int userNum = 0;
int i = 0;
userNum = 4; // Assume positive
cout << "userNum = " << userNum << endl;
while (i != userNum) {
i++;
cout << i;
}
cout << endl;
return 0;
}
The output will be
userNum = 4
1234
as you would've expected. There are many other good sources on how to use string formatting out there. I'll give some links here but it should be easy for you to search them as well.
Link 1 - cplusplus.com - basic input/output
Link 2 - SOF
I hope it helped.
Hey guys I am new to reading txt files to arrays, so I need to read this txt file temperature.txt to a two dimensional array. Here is the file I need to read, and the code I tried writing up it complies but Im not sure if it is reading it correctly
T(F) R1 R2 R3 R4
95.0 95.20 66.10 43.10 29.00
96.0 96.10 67.60 43.50 31.20
97.0 97.40 67.00 43.70 30.50
98.0 97.20 69.10 44.10 30.70
99.0 98.90 68.00 44.70 32.80
100.0 99.50 71.10 45.10 31.50
101.0 101.00 71.20 45.30 31.60
102.0 101.60 71.00 45.70 30.50
103.0 101.80 73.10 46.30 32.50
104.0 103.70 73.50 46.60 32.70
105.0 105.60 72.80 47.10 33.60
UPDATE I re did this again without looking at your answers but will this work ?
using namespace std;
#include<fstream>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<stdlib.h>
int main ()
{
char temp[11] [5];
ifstream tempin ("c:\\mydoc2\\temperaturedata.txt");
tempin>>temp[0]>>temp[1]>>temp[2]>>temp[3]>>temp[4]>>temp[5]>>temp[6]>>temp[7]>>temp[8]
>>temp[9]>>temp[10];
while(!tempin.fail())
{
cout<< temp[0] << " " << temp[1] << " " << temp[2] << " " << temp[3]<< " " << temp[4]<< " " << temp[5] << " " << temp [6] <<
" " << temp [7] << " " << temp[8] << " " << temp[9] << " " << temp[10];
tempin>>temp[0]>>temp[1]>>temp[2]>>temp[3]>>temp[4]>>temp[5]>>temp[6]>>temp[7]
>>temp[8]>>temp[9]>>temp[10];
}
cout << endl << endl;
system("pause");
return 0;
}
You have a string myArray[5]; but you're reading 55 elements - that should not work!
There are lots of errors in your code.
1) You have written a read function but you never call it, so it never executes.
2) There is no 2D array in your code. 2D arrays look like this double myArray[10][10];. (that's a 10 by 10 2D array of doubles).
3) You're trying to read floating point numbers, but your array is an array of strings.
4) Your array is size 5 but you try and read 55 items into it.
5) After you open the file you have an infinite loop which just prints out "No file\n". Not sure why you want to print out error messages in a loop. Normally you just print an error message once.
I could go on, but I think the main point is that you're a beginner, and you currently aren't able to write three lines of code without introducing an error (sorry to be harsh but based on the above that is true). So the important lesson is that you should not try to write more than three lines of code at once.
Try something like this
a) Write some code which opens a file, test it and check that it does open the file
b) Add some code to a) to read one number, test it and check that it does read one number.
c) Replace the read one number code with code that reads a 1D array of numbers. Test it and check that it works.
etc. etc.
The point is to build up gradually to the program you want, and test each stage as you go. I can't emphasise how important that is. Every professional programmer works like this, but because you're a beginner the steps you have to take are much smaller than an experienced programmer.
Try something like this:
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
string line;
ifstream myfile ("C:/temps.txt");
int dim_x = 12;
int dim_y = 5;
double temps[dim_x][dim_y] ;
//init the array if neccesary
for(int x = 0;x<dim_x;x++)
for(int y = 0; y<dim_y;y++)
temps[x][y]=0;
if (myfile.is_open()){
for ( int x=0; getline (myfile,line); x++ ){
int y=0;
istringstream iss(line);
while(iss){
string sub;
iss >> sub;
temps[x][y] = ::atof(sub.c_str());
y++;
}
}
myfile.close();
}
cout << "TEMPS:" << endl;
for(int x = 0;x<dim_x;x++){
for(int y = 0; y<dim_y;y++)
cout<<temps[x][y]<<" ";
cout<<endl;
}
return 0;
}
I made some improvements
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void read ();
int main ()
{
read();
return 0;
}
void read()
{
ifstream indata(".\\temperaturedata.txt");
if(indata == NULL)
{
cout<< "Opening file failed."<< endl;
return;
}
const int columns = 5;
const int rows = 11;
double myArray[rows][columns];
string tmp;
getline(indata, tmp);
for(int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
cout << "\t" << flush;
indata >> myArray[i][j];
cout.setf(ios::fixed);
cout << setprecision(2) << myArray[i][j] <<flush;
}
cout << endl;
}
indata.close();
}
If the content of your file is like this:
95.0 95.20 66.10 43.10 29.00
96.0 96.10 67.60 43.50 31.20
97.0 97.40 67.00 43.70 30.50
98.0 97.20 69.10 44.10 30.70
99.0 98.90 68.00 44.70 32.80
100.0 99.50 71.10 45.10 31.50
101.0 101.00 71.20 45.30 31.60
102.0 101.60 71.00 45.70 30.50
103.0 101.80 73.10 46.30 32.50
104.0 103.70 73.50 46.60 32.70
105.0 105.60 72.80 47.10 33.60
then, it's quite easy for you to get these values. But there are some errors in your code:
while(!indata.fail()) : This line will cause a dead loop. Use if(!indata) instead.
You will need a 2-dimension array of type double instead of string
Here is what could work:
#include<fstream>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<stdlib.h>
using namespace std;
void read ();
int main ()
{
read();
system("PAUSE");
return 0;
}
void read()
{
ifstream indata("E:\\temperature.txt"); //that's my path,you should use yours.
if(!indata)
{
cout<<"No file."<< endl;
}
if(indata.is_open())
{
double myArray[11][5];
for(int i = 0; i < 11; ++i)
{
for(int j = 0; j < 5; ++j)
{
indata >> myArray[i][j];
//cout<<myArray[i][j]<<"\t";
}
//cout<<endl;
}
}
}
This could work when your txt file doesn't include the first line:T(F) R1 R2 R3 R4, if this line did exit,you should use getline() to move your file pointer to the second line, where you could read the data.