where do i put a while loop? - visual-c++

In an English class, a student is given 4 term tests (each marked out of 50) and one final exam (marked
out of 100). Each term test is weighted at 20% of the overall mark for the course and the final exam
is also weighted at 20%. Write a program to read marks for the 4 term tests followed by the mark for
the final exam. The program then printsthe final overall mark as well asthe grade. The grading scheme
follows. A (75-100), B (60-74), C (50-59), F (under 50).
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream infile("input.txt");
if (infile.is_open())
cout<<"File is opened"<<endl;
else{
cout<<"Unable to open file"<<endl;
exit (1);
}
int id, test1, test2, test3, test4, final1;
infile>>id>>test1>>test2>>test3>>test4>>final1;
float tests, finals, grade;
tests = ((test1+test2+test3+test4)/200.0)*80;
finals= (final1/100.0)*20;
grade= tests+finals;
cout<<"ID"<<"\t"<<"%"<<"\t"<<"Grade"<<endl;
if(grade>=75)
cout<<id<<"\t"<<grade<<"\t"<<"A"<<endl;
else if(grade>=60)
cout<<id<<"\t"<<grade<<"\t"<<"B"<<endl;
else if(grade>=50)
cout<<id<<"\t"<<grade<<"\t"<<"C"<<endl;
else
cout<<id<<"\t"<<grade<<"\t"<<"F"<<endl;
infile>>id>>test1>> test2>>test3>>test4>>final1;
infile.close();
}

Related

Generating a random sample of integers with unequal probability in Rcpp

I am trying to use the Rcpp sample function, but I want to sample without replacement and with unequal probability. However I am struggling to understand what form the argument sugar::probs_t probs should take, because I cannot find the definition.
sugar::probs_t is a typedef of Nullable< Vector<REALSXP> > (see the inst/include/Rcpp/sugar/functions/sample.h code file). So, if you pass it a Rcpp::NumericVector, then everything should be fine.
As you didn't provide any example code, lets look at an implementation in the unit test file for sugar:
// [[Rcpp::export]]
NumericVector sample_dbl(NumericVector x, int sz, bool rep = false, sugar::probs_t p = R_NilValue)
{
return sample(x, sz, rep, p);
}

Writing a C program to solve an equation numerically

I am trying to solve x-cos(x)=0 numerically.
I need the program to accept one argument on the command line that becomes the desired accuracy of the solution.
The solution should yield an answer within some +/- the specified accuracy (epsilon) of 0 when the equation x-cos(x) is evaluated.
The maximum number of iterations should be set to 100.
The program should start with a first guess value of x=0.
The desired accuracy should accept both floating and scientific notation formats.
There should be a warning message if too few or too many arguments are supplied, and therefore exit the program.
If a solution is found in the max iterations, it should print the solution, accuracy and number of iterations.
If no solution is achieved in the max iterations, the program should print a message to indicate as such and then close.
Find the smallest accuracy that can be achieved in max iterations in powers of 10.
I know that there are loops involved. I've started it as such:`
#include<stdio.h>
#include<math.h>
int
main(void)
{
int MAX_ITERATIONS[100],x=0;
float epsilon;
double epsilon;
x=cos[x];
for (x=0; x<MAX_ITERATIONS; ++x)
if (MAX_ITERATIONS < x)
x=MAX_ITERATIONS[100];
}
I am not sure where to go from here or if I am even on the right track.
Here is some code to help you get started. My philosophy is to make only small changes and always keep a copy of what was working before. The way when I break something, I know exactly where I broke it. This code does not do everything you want, but you can make those changes yourself. To compile the code, I used cc -lm progname.c. To execute it, I used ./a.out 0.002.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
double delta, x;
double epsilon=0.001;
double previous = 1.0;
if (argc > 1)
epsilon = strtof(argv[1], NULL);
printf("Using epsilon = %12.8f\n", epsilon);
for (x=0.1; x<1.0; x+=epsilon) {
delta = fabs(x-cos(x));
if (delta < previous)
previous = delta;
else
break;
}
printf("%12.8f %12.8f %12.8f\n", x, cos(x), delta);
}

CUDA Programming: Compilation Error

I am making a CUDA program that implements the data parallel prefix sum calculation operating upon N numbers. My code is also supposed to generate the numbers on the host using a random number generator. However, I seem to always run into a "unrecognized token" and "expected a declaration" error on the ending bracket of int main when attempting to compile. I am running the code on Linux.
#include <stdio.h>
#include <cuda.h>
#include <stdlib.h>
#include <math.h>
__global__ void gpu_cal(int *a,int i, int n) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if(tid>=i && tid < n) {
a[tid] = a[tid]+a[tid-i];
}
}
int main(void)
{
int key;
int *dev_a;
int N=10;//size of 1D array
int B=1;//blocks in the grid
int T=10;//threads in a block
do{
printf ("Some limitations:\n");
printf (" Maximum number of threads per block = 1024\n");
printf (" Maximum sizes of x-dimension of thread block = 1024\n");
printf (" Maximum size of each dimension of grid of thread blocks = 65535\n");
printf (" N<=B*T\n");
do{
printf("Enter size of array in one dimension, currently %d\n",N);
scanf("%d",&N);
printf("Enter size of blocks in the grid, currently %d\n",B);
scanf("%d",&B);
printf("Enter size of threads in a block, currently %d\n",T);
scanf("%d",&T);
if(N>B*T)
printf("N>B*T, this will result in an incorrect result generated by GPU, please try again\n");
if(T>1024)
printf("T>1024, this will result in an incorrect result generated by GPU, please try again\n");
}while((N>B*T)||(T>1024));
cudaEvent_t start, stop; // using cuda events to measure time
float elapsed_time_ms1, elapsed_time_ms3;
int a[N],gpu_result[N];//for result generated by GPU
int cpu_result[N];//CPU result
cudaMalloc((void**)&dev_a,N * sizeof(int));//allocate memory on GPU
int i,j;
srand(1); //initialize random number generator
for (i=0; i < N; i++) // load array with some numbers
a[i] = (int)rand() ;
cudaMemcpy(dev_a, a , N*sizeof(int),cudaMemcpyHostToDevice);//load data from host to device
cudaEventCreate(&start); // instrument code to measure start time
cudaEventCreate(&stop);
cudaEventRecord(start, 0);
//GPU computation
for(j=0;j<log(N)/log(2);j++){
gpu_cal<<<B,T>>>(dev_a,pow(2,j),N);
cudaThreadSynchronize();
}
cudaMemcpy(gpu_result,dev_a,N*sizeof(int),cudaMemcpyDeviceToHost);
cudaEventRecord(stop, 0); // instrument code to measue end time
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsed_time_ms1, start, stop );
printf("\n\n\nTime to calculate results on GPU: %f ms.\n", elapsed_time_ms1); // print out execution time
//CPU computation
cudaEventRecord(start, 0);
for(i=0;i<N;i++)
{
cpu_result[i]=0;
for(j=0;j<=i;j++)
{
cpu_result[i]=cpu_result[i]+a[j];
}
}
cudaEventRecord(stop, 0); // instrument code to measue end time
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsed_time_ms3, start, stop );
printf("Time to calculate results on CPU: %f ms.\n\n", elapsed_time_ms3); // print out execution time
//Error check
for(i=0;i < N;i++) {
if (gpu_result[i] != cpu_result[i] ) {
printf("ERROR!!! CPU and GPU create different answers\n");
break;
}
}
//Calculate speedup
printf("Speedup on GPU compared to CPU= %f\n", (float) elapsed_time_ms3 / (float) elapsed_time_ms1);
printf("\nN=%d",N);
printf("\nB=%d",B);
printf("\nT=%d",T);
printf("\n\n\nEnter '1' to repeat, or other integer to terminate\n");
scanf("%d",&key);
}while(key == 1);
cudaFree(dev_a);//deallocation
return 0;
}​
The very last } in your code is a Unicode character. If you delete this entire line, and retype the }, the error will be gone.
There are two compile errors in your code.
First, Last ending bracket is a unicode character, so you should resave your code as unicode or delete and rewrite the last ending bracket.
Second, int type variable N which used at this line - int a[N],gpu_result[N];//for result generated by GPU
was declared int type, but it's not allowed in c or c++ compiler, so you should change the N declaration as const int N.

Making a metric between colors (perception model) with "difference"

Take a look at the image below. If you're not color blind, you should see some A's and B's. There are 3 A's and 3 B's in the image, and they all have one thing in common: Their color is the background + 10% of value, saturation and hue, in that order. For most people, the center letters are very hard to see - saturation doesn't do much, it seems!
This is a bit troublesome though because I'm making some character recognition software, and I'm filtering the image based on known foreground and background colors. But sometimes these are quite close, while the image is noisy. In order to decide whether a pixel belongs to a letter or to the background, my program checks Euclidean RGB distance:
(r-fr)*(r-fr) + (g-fg)*(g-fg) + (b-fb)*(b*fb) <
(r-br)*(r-br) + (g-bg)*(g-bg) + (b-bb)*(b*bb)
This works okay, but for close backgrounds and foregrounds, it works pretty bad sometimes.
Are there some better metrics to look for? I've looked into color perception models but those mostly model brightness rather than perceptive difference which I'm looking for. Maybe one that models saturation as less effective, and certain hue differences also? Any pointers to some interesting metrics would be very useful.
As was mentioned in the comments, the answer is using a perceptual color space, but I thought I'd throw together a visual example of how the edge detection behaves in the two color spaces. (Code is at the end.) In both cases, the Sobel edge detection is performed on the 3-channel color image, and then the result is flattened to gray scale.
RGB space:
L*a*b space (image is logarithmic, as the edges on the third letters are much more significant than the edges on the first letters, which are more significant than the edges on the second letters):
OpenCV C++ code:
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "iostream"
using namespace cv;
using namespace std;
void show(const char *name, Mat &img, int dolog=0)
{
double minVal, maxVal;
minMaxLoc(img, &minVal, &maxVal);
cout << name << " " << "minVal : " << minVal << endl << "maxVal : " << maxVal << endl;
Mat draw;
if(dolog) {
Mat shifted, tmp;
add(img, minVal, shifted);
log(shifted, tmp);
minMaxLoc(tmp, &minVal, &maxVal);
tmp.convertTo(draw, CV_8U, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
} else {
img.convertTo(draw, CV_8U, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
}
namedWindow(name, CV_WINDOW_AUTOSIZE);
imshow(name, draw);
imwrite(name, draw);
}
int main( )
{
Mat src;
src = imread("AAABBB.png", CV_LOAD_IMAGE_COLOR);
namedWindow( "Original image", CV_WINDOW_AUTOSIZE );
imshow( "Original image", src );
Mat lab, gray;
cvtColor(src, lab, CV_BGR2Lab);
Mat sobel_lab, sobel_bgr;
Sobel(lab, sobel_lab, CV_32F, 1, 0);
Sobel(src, sobel_bgr, CV_32F, 1, 0);
Mat bgr_sobel_lab, gray_sobel_lab;
cvtColor(sobel_lab, bgr_sobel_lab, CV_Lab2BGR);
show("lab->bgr edges.png", bgr_sobel_lab, 1);
cvtColor(bgr_sobel_lab, gray_sobel_lab, CV_BGR2GRAY);
Mat gray_sobel_bgr;
cvtColor(sobel_bgr, gray_sobel_bgr, CV_BGR2GRAY);
show("lab edges.png", gray_sobel_lab, 1);
show("bgr edges.png", gray_sobel_bgr);
waitKey(0);
return 0;
}

picking up random numbers from a text file in c++

If a text file contains numbers in 100 rows * 100 columns (for example). Now i want my program to pick up ,for example , one number from 60th row and 97th column and then assign this value to a variable and perform some calculation with this variable. So i want to pick up some random numbers from a text file which contains a lot of numbers. how can i do that??
I made a code for practice but its giving some error.
the text file contains 6 different digits in 2 rows and 3 columns
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
int data[6],i=0;
ifstream myfile;
myfile.open ("a.txt");
while (i<<6)
{
myfile>>data[i];
i=i+1;
}
myfile.close();
cout<<data[0]<<"\t"<<data[1]<<"\t"<<data[2]<<"\t"<<data[3]<<"\t"<<data[4]<<"\t" <<data[5]<<"\n";
system("pause");
return 0;
}
while (i < 6)
{
myfile>>data[i];
i=i+1;
}

Resources