确定平均测验成绩的程序

时间:2019-05-06 23:12:17

标签: c

该程序应该获取包含学生测验成绩的文本文件,并将其写入包含学生姓名的另一个文件中,并为学生分配成绩

package com.app.tunzahub.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.app.tunzahub.Config;
import com.app.tunzahub.R;
import com.app.tunzahub.fragments.FragmentAbout;
import com.app.tunzahub.tab.FragmentTabCategory;
import com.app.tunzahub.tab.FragmentTabFavorite;
import com.app.tunzahub.tab.FragmentTabRecent;
import com.app.tunzahub.utils.Constant;
import com.app.tunzahub.utils.GDPR;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private final static String COLLAPSING_TOOLBAR_FRAGMENT_TAG = "collapsing_toolbar";
    private final static String SELECTED_TAG = "selected_index";
    private static int selectedIndex;
    private final static int COLLAPSING_TOOLBAR = 0;
    ActionBarDrawerToggle actionBarDrawerToggle;
    private DrawerLayout drawerLayout;
    BroadcastReceiver broadcastReceiver;
    NavigationView navigationView;
    private long exitTime = 0;
    private AdView adView;
    View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view = findViewById(android.R.id.content);

        if (Config.ENABLE_RTL_MODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
            }
        } else {
            Log.d("Log", "Working in Normal Mode, RTL Mode is Disabled");
        }

        loadBannerAd();

        navigationView = findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(this);
        drawerLayout = findViewById(R.id.drawer_layout);

        if (savedInstanceState != null) {
            navigationView.getMenu().getItem(savedInstanceState.getInt(SELECTED_TAG)).setChecked(true);
            return;
        }

        selectedIndex = COLLAPSING_TOOLBAR;
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, new FragmentTabRecent(), COLLAPSING_TOOLBAR_FRAGMENT_TAG)
                .commit();

        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
                    // now subscribe to global topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);

                } else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
                    // new push notification is received
                    String message = intent.getStringExtra("message");
                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
                }
            }
        };

        GDPR.updateConsentStatus(this);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_TAG, selectedIndex);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {

            case R.id.search:
                Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
                startActivity(intent);
                return true;

            default:
                return super.onOptionsItemSelected(menuItem);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

        switch (menuItem.getItemId()) {
            case R.id.drawer_recent:
                if (!menuItem.isChecked()) {
                    menuItem.setChecked(true);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragment_container, new FragmentTabRecent(), COLLAPSING_TOOLBAR_FRAGMENT_TAG)
                            .commit();
                }
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;

            case R.id.drawer_category:
                if (!menuItem.isChecked()) {
                    menuItem.setChecked(true);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragment_container, new FragmentTabCategory(), COLLAPSING_TOOLBAR_FRAGMENT_TAG)
                            .commit();
                }
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;

            case R.id.drawer_favorite:
                menuItem.setChecked(true);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_container, new FragmentTabFavorite(), COLLAPSING_TOOLBAR_FRAGMENT_TAG)
                        .commit();

                drawerLayout.closeDrawer(GravityCompat.START);
                return true;

            case R.id.drawer_rate:

                final String appName = getPackageName();
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
                } catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
                }

                return true;

            case R.id.drawer_more:

                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));

                return true;

            case R.id.drawer_share:

                String app_name = android.text.Html.fromHtml(getResources().getString(R.string.app_name)).toString();
                String share_text = android.text.Html.fromHtml(getResources().getString(R.string.share_text)).toString();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, app_name + "\n\n" + share_text + "\n\n" + "https://play.google.com/store/apps/details?id=" + getPackageName());
                sendIntent.setType("text/plain");
                startActivity(sendIntent);

                return true;

            case R.id.drawer_about:
                if (!menuItem.isChecked()) {
                    menuItem.setChecked(true);
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            new FragmentAbout(), COLLAPSING_TOOLBAR_FRAGMENT_TAG).commit();
                }
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;

        }
        return false;
    }

    public void setupNavigationDrawer(Toolbar toolbar) {
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            exitApp();
        }
    }

    public void exitApp() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    public void loadBannerAd() {
        if (Config.ENABLE_ADMOB_BANNER_ADS) {
            adView = findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter.class, GDPR.getBundleAd(MainActivity.this)).build();
            adView.loadAd(adRequest);
            adView.setAdListener(new AdListener() {

                @Override
                public void onAdClosed() {
                }

                @Override
                public void onAdFailedToLoad(int error) {
                    adView.setVisibility(View.GONE);
                }

                @Override
                public void onAdLeftApplication() {
                }

                @Override
                public void onAdOpened() {
                }

                @Override
                public void onAdLoaded() {
                    adView.setVisibility(View.VISIBLE);
                }
            });

        } else {
            Log.d("AdMob", "AdMob Banner is Disabled");
        }
    }

}
#include <stdio.h>
#include <stdlib.h>

void format(FILE *outputFile);
void copyNames(FILE *inputFile, FILE *outputFile);
void copyScores(FILE *inputFile, FILE *outputFile);

int main(int argc, char *argv[]) {
    FILE *input, *output;
    char firstname[50], lastname[50];
    int score, n, total;

    input = fopen("quiz.txt", "r");
    output = fopen("average.txt", "w");
    if (input == NULL || output == NULL) {
        printf("ERROR: The file(s) could not be opened!");
        return 1;
    }

    while (fscanf(input, "%49s%49s", firstname, lastname) == 2) {
        fprintf(output, "%s %s", firstname, lastname);
        for (n = 0, total = 0; fscanf(input, "%d", &score) == 1; n++) {
            fprintf(output, " %d", score);
            total += score;
        }
        fprintf(output, " %.2f\n", n == 0 ? 0.0 : (double)total / n);
    }
    fclose(input);
    fclose(output);

    return 0;
}


void copyNames(FILE *inputFile, FILE *outputFile){
    char firstName[10], lastName[10], ch;
    ch = fgetc(inputFile); //sets ch to a place in the file
    fseek(inputFile, 0, SEEK_SET); //resets ch so it is at the beginning of the file
    while (ch != EOF){
        int i = 0, j = 0; //resets values in the array so you can overwrite it
        for (ch = fgetc(inputFile); ch != ' ' && ch != EOF; ch = fgetc(inputFile)){ //gets the first name and puts it into an array
            firstName[i] = ch;
            i++;
        }
        for (ch = fgetc(inputFile); ch != ' ' && ch != EOF; ch = fgetc(inputFile)){ //gets last name and puts it into array
            lastName[j] = ch;
            j++;
        }
        lastName[j] = '\0'; //truncates the arrays
        firstName[i] = '\0';
        while (ch != '\n' && ch != EOF){ //moves the placement of ch to avoid all the grades to get the next name
            ch = fgetc(inputFile);
        }
        fprintf(outputFile, "%s, %s \n", lastName, firstName); //prints the names to the output file
    }
}

void copyScores(FILE *inputFile, FILE *outputFile){
    fseek(inputFile, 0, SEEK_SET); //resets fgetc again
    char lineMemory[60], sc = fgetc(inputFile);
    while (sc != EOF){
        int i = 0, num = 0, scores[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        for (sc = fgetc(inputFile); sc != '\n' && sc != EOF; sc = fgetc(inputFile)){ //writes the whole line into an array
            lineMemory[i] = sc;
            i++;
        }
        lineMemory[i] = '\0'; //truncates the array
        for (int check = 0; lineMemory[check] != '\0'; check++){ //walks through the string
            if (isdigit(lineMemory[check]) != 0){ //looks for the digits in the string
                int j = lineMemory[check] - '0'; //turns the characters into integers
                scores[num] = j; //puts the integer into the array
                num++;
            }
        }
        float avg, total = 0;
        for (int indx = 0; indx < 10; indx++){
            total += scores[indx];
        }
        avg = total / 10; //finds average of the grades
        for (int x = 0; x < 10; x++){
            fprintf(outputFile, "%2d", scores[x]); //prints the quiz grades
        }
        fprintf(outputFile, "%10g\n", avg); //prints the average
    }
}

void copyAll(FILE *inputFile, FILE *outputFile){
    char ch = fgetc(inputFile);

    while (ch != EOF){
        ch = fgetc(inputFile);
        fputc(ch, outputFile);
    }
    printf("Data successfully written.\n");
}
     

Smith, Alex 98 100 90 82 92.5 Adams, John 100 90 82 90 90.5 在名称和平均值之间有四个空格
   // 92.5和90.5是平均值。

但是我的代码只显示了名称,并在名称下方显示了等级。喜欢:

//
     

等...

1 个答案:

答案 0 :(得分:2)

  

但是我的代码只显示了名称,并在名称下方显示了等级。喜欢:

恐怕发布的代码将不再具有此输出:您复制了my answer's code来替代main函数,该函数的输出应该比预期的要近得多。但是您应该:

  • 删除不再有用的其他功能
  • 稍微调整printf使其与更新后的问题陈述相符:

    fprintf(output, "%s, %s   ", lastname, firstname);
    
  • 调整平均值printf以输出一个小数:

    fprintf(output, " %.1f\n", n == 0 ? 0.0 : (double)total / n);
    

但是请注意,问题陈述不一致:

Smith, Alex    98 100 90 82 92.5
Adams, John    100 90 82 90 90.5
     

名称和平均值之间有四个空格
   92.590.5是平均值。

名字和第一年级之间出现4个空格,他的平均值出现在所有年级之后,与最后一个年级分开一个空格。