C
Skor hesaplama
Skor hesaplama fonksiyonuyla doğru sayısını öğrenirsin.
Skor hesaplama
Dördüncü ders print_percentage fonksiyonunu tanımlar. Bu fonksiyon, skoru yüzdelik olarak hesaplar ve ekrana yazar. Yüzde, başarı oranını net gösterir.
İmza: void print_percentage(int score, int count). Gövde: int pct = score * 100 / count; printf("Yüzde: %d%%\n", pct);. Burada %% ekrana tek % yazar. Hesap önce score * 100 yapar, sonra count'a böler; bu sıra önemlidir, çünkü tamsayı bölmede score / count * 100 yanlış sonuç verebilir. Önceki dersin çözümü başlangıç koduna dahildir.
Tamsayı bölme
C'de tamsayı bölme kesir kısmını atar. Bu, yüzde hesaplarken işlemlerin sırasını önemli yapar. Doğru sıra: önce çarp, sonra böl.
Örnek: 2 * 100 / 2 = 100 (doğru). Ama 2 / 2 * 100 = 100 de doğru. Sorun, küçük değerlerde ortaya çıkar: 1 / 2 * 100 = 0 * 100 = 0 (yanlış, 50 olmalı). Oysa 1 * 100 / 2 = 100 / 2 = 50 (doğru). Bu yüzden score * 100 / count sırası güvenlidir. Tamsayı bölme dikkat ister; float gerekirse (float) dönüşümü kullanılır.
Uygulama print_percentage fonksiyonunu yaz
void print_percentage(int score, int count) yaz. Gövdede int pct = score * 100 / count; hesapla ve printf("Yüzde: %d%%\n", pct); ile yazdır. main içinde print_percentage(score, count); çağır (score ve count önceki derslerden gelir).
Örnek çözümü göster
#include <stdio.h>
#include <string.h>
struct Question {
char text[64];
int correct;
};
void add_question(struct Question *q, int *count, const char *text, int correct) {
strcpy(q[*count].text, text);
q[*count].correct = correct;
(*count)++;
}
int run_quiz(struct Question *q, int count) {
int answers[3] = {0, 1, 2};
int score = 0;
for (int i = 0; i < count; i++) {
printf("Soru %d: %s\n", i + 1, q[i].text);
if (answers[i] == q[i].correct) {
score++;
}
}
return score;
}
void print_percentage(int score, int count) {
int pct = score * 100 / count;
printf("Yüzde: %d%%\n", pct);
}
int main(void) {
struct Question questions[10];
int count = 0;
add_question(questions, &count, "Başkent?", 0);
add_question(questions, &count, "2+2?", 1);
printf("%d soru eklendi\n", count);
int score = run_quiz(questions, count);
printf("Skor: %d\n", score);
print_percentage(score, count);
return 0;
}
Kendini test et
-
Yüzde parçalarını eşle
- score * 100 / count
- Yüzde hesabı
- %d%%
- Yüzde formatı
- printf("Yüzde:")
- Çıktı
- void print_percentage
- Fonksiyon imzası
-
2 * 100 / 2 işleminin sonucu?
Cevabı göster
100 — 2*100=200, 200/2=100. Tamsayı bölme doğru verir.
-
Yüzde hesabını tamamla
int pct = score ____ / count;
Cevabı göster
int pct = score * 100 / count;
Sıradaki ders: Birleştirme